package com.dhcc.bpm.modules.log.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dhcc.bpm.alarm.entity.statistic.AlarmStatistic;
import com.dhcc.bpm.alarm.service.IAlarmStatisticService;
import com.dhcc.bpm.common.annotation.Log;
import com.dhcc.bpm.common.enums.BusinessType;
import com.dhcc.bpm.common.utils.*;
import com.dhcc.bpm.modules.alarm.service.IAlarmNoticeService;
import com.dhcc.bpm.modules.alarm.vo.AlarmNoticeVO;
import com.dhcc.bpm.modules.api.entity.BaseProduct;
import com.dhcc.bpm.modules.api.entity.Product;
import com.dhcc.bpm.modules.api.entity.Sys;
import com.dhcc.bpm.modules.api.service.IApiService;
import com.dhcc.bpm.modules.api.service.IBaseProductService;
import com.dhcc.bpm.modules.api.service.IProductService;
import com.dhcc.bpm.modules.api.service.ISysService;
import com.dhcc.bpm.modules.api.vo.ApiVO;
import com.dhcc.bpm.modules.log.entity.*;
import com.dhcc.bpm.modules.log.service.*;
import com.dhcc.bpm.modules.log.vo.*;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.xkcoding.http.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import net.sf.json.JSONObject;
import org.slf4j.LoggerFactory;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.*;


/**
 * @ClassName GatewayLogDayController.class
 * @Description 网关访问记录天表 控制器
 * @Author xiaFaYu
 * @Date 2020-02-03 14:16
 * @Version V1.0
 * @Copyright: 2020 东华软件 . All rights reserved.
 */
@RestController
@AllArgsConstructor
@RequestMapping("bpm-system/gatewaylogday")
@Api(value = "", tags = "接口")
public class GatewayLogDayController extends BladeController {
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplateUtil redisUtil;

    private IGatewayLogDayService gatewayLogDayService;

    private IGatewayLogMinuteService gatewayLogMinuteService;

    private IGatewayLogService gatewayLogService;

    private static org.slf4j.Logger logger = LoggerFactory.getLogger(GatewayLogDayController.class);

    private IApiService apiService;

    private IProductService productService;

    private IBaseProductService baseProductService;

    private IAlarmNoticeService alarmNoticeService;

    private ITpsService tpsService;

    private ITpsPeakService tpsPeakService;

    @Autowired
    private IAlarmStatisticService alarmStatisticService;

    @Autowired
    private ISysService sysService;

    private static final String tpsNum = "tpsNum:";
    private static final String linkNum = "linkNum:";

    public static int processors = Runtime.getRuntime().availableProcessors();
    public static ThreadPoolExecutor executor = new ThreadPoolExecutor(processors * 5, processors * 10, 60L, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(processors * 20),
            Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());

    /**
     * @param gatewayLogDay
     * @return org.springblade.core.tool.api.R<com.dhcc.bpm.modules.log.entity.GatewayLogDay>
     * @Description 详情
     * @Author xiafayu
     * @Date 2020/2/24 15:15
     **/
    @ApiLog("网关日访问记录详情")
    @GetMapping("/detail")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情", notes = "传入gatewayLogDay")
    @Log(title = "opc_gateway_log_day 详情", businessType = BusinessType.SELECT)
    public R<GatewayLogDay> detail(GatewayLogDay gatewayLogDay) {
        GatewayLogDay detail = gatewayLogDayService.getOne(Condition.getQueryWrapper(gatewayLogDay));
        return R.data(detail);
    }

    /**
     * @param gatewayLogDay
     * @param query
     * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage < com.dhcc.bpm.modules.log.entity.GatewayLogDay>>
     * @Description 分页
     * @Author xiafayu
     * @Date 2020/2/24 15:16
     **/
    @ApiLog("网关日访问记录分页")
    @GetMapping("/list")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页", notes = "传入gatewayLogDay")
    @Log(title = "opc_gateway_log_day 分页", businessType = BusinessType.SELECT)
    public R<IPage<GatewayLogDay>> list(GatewayLogDay gatewayLogDay, Query query) {
        IPage<GatewayLogDay> pages = gatewayLogDayService.page(Condition.getPage(query), Condition.getQueryWrapper(gatewayLogDay));
        return R.data(pages);
    }

    /**
     * @param gatewayLogDay
     * @param query
     * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage < com.dhcc.bpm.modules.log.vo.GatewayLogDayVO>>
     * @Description 自定义分页
     * @Author xiafayu
     * @Date 2020/2/24 15:16
     **/
    @GetMapping("/page")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "分页", notes = "传入gatewayLogDay")
    @Log(title = "opc_gateway_log_day 分页", businessType = BusinessType.SELECT)
    public R<IPage<GatewayLogDayVO>> page(GatewayLogDayVO gatewayLogDay, Query query) {
        IPage<GatewayLogDayVO> pages = gatewayLogDayService.selectGatewayLogDayPage(Condition.getPage(query), gatewayLogDay);
        return R.data(pages);
    }

    /**
     * @param gatewayLogDay
     * @return org.springblade.core.tool.api.R
     * @Description 新增
     * @Author xiafayu
     * @Date 2020/2/24 15:16
     **/
    @PostMapping("/save")
    @ApiLog("网关日访问记录新增")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增", notes = "传入gatewayLogDay")
    @Log(title = "opc_gateway_log_day 新增", businessType = BusinessType.INSERT)
    public R save(@Valid @RequestBody GatewayLogDay gatewayLogDay) {
        return R.status(gatewayLogDayService.save(gatewayLogDay));
    }

    /**
     * @param gatewayLogDay
     * @return org.springblade.core.tool.api.R
     * @Description 修改
     * @Author xiafayu
     * @Date 2020/2/24 15:16
     **/
    @PostMapping("/update")
    @ApiLog("网关日访问记录修改")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "修改", notes = "传入gatewayLogDay")
    @Log(title = "opc_gateway_log_day 修改", businessType = BusinessType.SELECT)
    public R update(@Valid @RequestBody GatewayLogDay gatewayLogDay) {
        return R.status(gatewayLogDayService.updateById(gatewayLogDay));
    }

    /**
     * @param gatewayLogDay
     * @return org.springblade.core.tool.api.R
     * @Description 新增或修改
     * @Author xiafayu
     * @Date 2020/2/24 15:17
     **/
    @PostMapping("/submit")
    @ApiLog("网关日访问记录新增修改")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "新增或修改", notes = "传入gatewayLogDay")
    @Log(title = "opc_gateway_log_day 新增或修改", businessType = BusinessType.UPDATE)
    public R submit(@Valid @RequestBody GatewayLogDay gatewayLogDay) {
        return R.status(gatewayLogDayService.saveOrUpdate(gatewayLogDay));
    }


    /**
     * @param type
     * @param apiRankVo
     * @return org.springblade.core.tool.api.R<java.util.List < com.dhcc.bpm.modules.log.vo.OrgaRankVo>>
     * @Description 获取机构交易量排行，次数
     * @Author xiafayu
     * @Date 2020/2/24 15:17
     **/
    @GetMapping("/orgaRanking/{type}")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "机构交易量排行", notes = "传入gatewayLogDay")
    @Log(title = "首页机构交易量排行", businessType = BusinessType.SELECT)
    public R<List<OrgaRankVo>> orgaRanking(@PathVariable("type") String type, OrgaRankVo apiRankVo) throws ParseException {
        List<OrgaRankVo> rankVoList = new LinkedList<>();
        Query query = new Query();
        query.setCurrent(1);
        query.setSize(7);
        apiRankVo.setAuthFlag("1"); // 认证状态  1--已认证
        apiRankVo.setRankFlag("true");

        String nowDate = DateUtils.dateTime();
        IPage<OrgaRankVo> apiRankVoPage = null;

        // 本部门API列表
        Query query1 = new Query();
        query1.setCurrent(1);
        query1.setSize(999999999); // 不分页
        ApiVO api = new ApiVO();
        IPage<ApiVO> page = apiService.listInfo(Condition.getPage(query1), api); // 查当前登录部门API列表信息
        List<String> apiCodeList = new ArrayList<String>();
        if (page.getRecords() != null && page.getRecords().size() > 0) {
            for (ApiVO apiVO : page.getRecords()) {
                apiCodeList.add(apiVO.getApiCode());
            }
        }
        apiRankVo.setApiCodeList(apiCodeList);

        switch (type) {
            case "day":
                apiRankVo.setRequestDate(nowDate);
                apiRankVoPage = gatewayLogMinuteService.countOrgaNum(Condition.getPage(query), apiRankVo);
                rankVoList = apiRankVoPage.getRecords();
                break;
            case "week": // 近七日
                String begDate = "";
                try {
                    begDate = DateUtils.getLastDay(nowDate, 6);
                } catch (Exception e) {
                    logger.error("获取近七日日期失败");
                } finally {

                }
                apiRankVo.setBegDate(begDate);
                apiRankVo.setEndDate(nowDate);

                apiRankVoPage = gatewayLogDayService.countOrgaNum(Condition.getPage(query), apiRankVo);
                rankVoList = apiRankVoPage.getRecords();
                break;
            case "month": // 近30天
                String begDate_2 = "";
                try {
                    begDate_2 = DateUtils.getLastDay(nowDate, 29);
                } catch (Exception e) {
                    logger.error("获取近30日日期失败");
                } finally {

                }
                apiRankVo.setBegDate(begDate_2);
                apiRankVo.setEndDate(nowDate);
                apiRankVoPage = gatewayLogDayService.countOrgaNum(Condition.getPage(query), apiRankVo);
                rankVoList = apiRankVoPage.getRecords();
                break;
            case "year":
                List<String> dateList_3 = DateUtils.getMonthEveryDays(nowDate);
                String begDate_3 = nowDate.substring(0, 4) + "0101";
                String endDate_3 = nowDate.substring(0, 4) + "1231";
                apiRankVo.setBegDate(begDate_3);
                apiRankVo.setEndDate(endDate_3);
                apiRankVoPage = gatewayLogDayService.countOrgaNum(Condition.getPage(query), apiRankVo);
                rankVoList = apiRankVoPage.getRecords();
                break;
            default:
                break;
        }
        return R.data(rankVoList);
    }

    /**
     * @param type
     * @param apiRankVo
     * @param query
     * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage < com.dhcc.bpm.modules.log.vo.OrgaRankVo>>
     * @Description 获取机构交易量排行，次数，成功率---分页
     * @Author xiafayu
     * @Date 2020/2/24 15:17
     **/
    @GetMapping("/orgaRankingPage/{type}")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "机构交易量排行", notes = "传入gatewayLogDay")
    @Log(title = "首页机构交易量排行--分页", businessType = BusinessType.SELECT)
    public R<IPage<OrgaRankVo>> orgaRankingPage(@PathVariable("type") String type, OrgaRankVo apiRankVo, Query query) throws ParseException {
        List<OrgaRankVo> rankVoList = new LinkedList<>();
        String nowDate = DateUtils.dateTime();
        IPage<OrgaRankVo> rankVoPage = null;
        apiRankVo.setAuthFlag("1"); // 认证状态  1--已认证
        apiRankVo.setRankFlag("true");

        // 本部门API列表
        Query query1 = new Query();
        query1.setCurrent(1);
        query1.setSize(999999999); // 不分页
        ApiVO api = new ApiVO();
        IPage<ApiVO> page = apiService.listInfo(Condition.getPage(query1), api); // 查当前登录部门API列表信息
        List<String> apiCodeList = new ArrayList<String>();
        if (page.getRecords() != null && page.getRecords().size() > 0) {
            for (ApiVO apiVO : page.getRecords()) {
                apiCodeList.add(apiVO.getApiCode());
            }
        }
        apiRankVo.setApiCodeList(apiCodeList);

        switch (type) {
            case "day":
                apiRankVo.setRequestDate(nowDate);
                rankVoPage = gatewayLogMinuteService.countOrgaNum(Condition.getPage(query), apiRankVo);
                rankVoList = rankVoPage.getRecords();
                break;
            case "week":
                String begDate = "";
                try {
                    begDate = DateUtils.getLastDay(nowDate, 6);
                } catch (Exception e) {
                    logger.error("获取近七日日期失败");
                } finally {

                }
                apiRankVo.setBegDate(begDate);
                apiRankVo.setEndDate(nowDate);
                rankVoPage = gatewayLogDayService.countOrgaNum(Condition.getPage(query), apiRankVo);
                rankVoList = rankVoPage.getRecords();
                break;
            case "month":
                String begDate_2 = "";
                try {
                    begDate_2 = DateUtils.getLastDay(nowDate, 29);
                } catch (Exception e) {
                    logger.error("获取近30日日期失败");
                } finally {

                }
                apiRankVo.setBegDate(begDate_2);
                apiRankVo.setEndDate(nowDate);
                rankVoPage = gatewayLogDayService.countOrgaNum(Condition.getPage(query), apiRankVo);
                rankVoList = rankVoPage.getRecords();
                break;
            case "year":
                String begDate_3 = nowDate.substring(0, 4) + "0101";
                String endDate_3 = nowDate.substring(0, 4) + "1231";
                apiRankVo.setBegDate(begDate_3);
                apiRankVo.setEndDate(endDate_3);
                rankVoPage = gatewayLogDayService.countOrgaNum(Condition.getPage(query), apiRankVo);
                rankVoList = rankVoPage.getRecords();
                break;
            default:
                break;
        }

        Integer rank = 0;
        if (rankVoList != null && rankVoList.size() > 0) {
            for (OrgaRankVo vo : rankVoList) {
                // 今日交易量
                Long todayNum = 0L;
                if (type.equals("week") || type.equals("month") || type.equals("year")) {
                    OrgaRankVo today = new OrgaRankVo();
                    today.setRequestDate(nowDate);
                    today.setEnv(apiRankVo.getEnv());
                    today.setOrgaId(vo.getOrgaId());
                    apiRankVo.setRankFlag("true");
                    IPage<OrgaRankVo> todayPage = gatewayLogMinuteService.countOrgaNum(Condition.getPage(query), today);

                    if (todayPage.getRecords() != null && todayPage.getRecords().size() > 0 && todayPage.getRecords().get(0) != null && todayPage.getRecords().get(0).getNum() != null) {
                        OrgaRankVo todayData = todayPage.getRecords().get(0);
                        todayNum = todayData.getNum();// 今日数据
                    }
                } else {
                    todayNum = vo.getNum();
                }

                // 统计昨日交易量
                ApiRankVo apiRankVo1 = new ApiRankVo();
                String lastDate = "";
                try {
                    lastDate = DateUtils.getLastDay(nowDate, 1);
                    apiRankVo1.setRequestDate(lastDate);
                    apiRankVo1.setOrgaCode(vo.getOpcOrgaCode());
                    apiRankVo1.setEnv(apiRankVo.getEnv());
                } catch (Exception e) {
                    logger.error("获取昨日日期失败");
                } finally {

                }

                String rate = "";
                String flag = "";
                Long lastDayNum = gatewayLogDayService.countLastDayApiNum(apiRankVo1);
                if (lastDayNum.equals(0L) && todayNum.equals(0L)) {
                    rate = "0";
                    flag = "middle";
                } else if (lastDayNum.equals(0L) && !todayNum.equals(0L)) {
                    rate = "100";
                    flag = "up";
                } else {
                    DecimalFormat df = new DecimalFormat("0");//格式化小数
                    rate = df.format((float) (todayNum - lastDayNum) / lastDayNum * 100);//返回的是String类型
                    if ("-".equals(rate.substring(0, 1))) {
                        rate = rate.replaceAll("-", "");
                        flag = "down";
                    } else {
                        flag = "up";
                    }
                }

                // 平均响应时间
                DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                double avgResTime = 0.00;
                if (vo.getLineNum() != 0) {
                    avgResTime = Double.valueOf(df.format(vo.getResponseTime() / vo.getLineNum()));
                }

                // 成功率
                String successRate = "0";
                if (vo.getNum() != null && vo.getNum() != 0) {
                    successRate = FormatUtils.doubleFormat((double) vo.getSuccessNum() / vo.getNum() * 100);//返回的是String类型
                }
                rank = rank + 1;
                vo.setRank(rank + ((query.getCurrent() - 1) * query.getSize()));
                vo.setSuccessRate(successRate + "%");
                vo.setResponseTime(avgResTime);
                vo.setFlag(flag);
                vo.setIncrease(rate + "%");
            }
        }

        rankVoPage.setRecords(rankVoList);
        return R.data(rankVoPage);
    }

    /**
     * @param ids
     * @return org.springblade.core.tool.api.R
     * @Description 删除
     * @Author xiafayu
     * @Date 2020/2/24 15:17
     **/
    @PostMapping("/remove")
    @ApiLog("网关日访问记录删除")
    @ApiOperationSupport(order = 8)
    @ApiOperation(value = "删除", notes = "传入ids")
    @Log(title = "opc_gateway_log_day 删除", businessType = BusinessType.DELETE)
    public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
        return R.status(gatewayLogDayService.removeByIds(Func.toLongList(ids)));
    }


// 开始多线程调用

    /**
     * @param apiRankVo
     * @param query
     * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage < com.dhcc.bpm.modules.log.vo.ApiRankVo>>
     * @Description 热门API排名
     * @Author xiafayu
     * @Date 2020/2/24 15:17
     **/
    @GetMapping("/apiIncrease")
    @ApiLog("网关日访问记录热门API排名")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "热门API排名", notes = "传入gatewayLogDay")
    @Log(title = "热门API排名", businessType = BusinessType.SELECT)
    public R<IPage<ApiRankVo>> apiRank(ApiRankVo apiRankVo, Query query) {
        // 分页为空的处理，避免设置排名报错
        if (query == null || query.getCurrent() == null || query.getSize() == null) {
            query = new Query();
            query.setCurrent(1);
            if ("workplace".equals(apiRankVo.getReqFlag())) {
                query.setSize(5);
            } else if ("orderTable".equals(apiRankVo.getReqFlag())) {
                query.setSize(10);
            } else {
                query.setSize(10);
            }
        }
        IPage<ApiRankVo> apiRankVoList = gatewayLogDayService.countApiNum(Condition.getPage(query), apiRankVo);
        final Integer[] rank = {0};
        String requestDate = DateUtils.dateTime();
        List<Future<ApiRankVo>> futures = new ArrayList<>();
        if (apiRankVoList.getRecords() != null && apiRankVoList.getRecords().size() > 0) {
            double maxPageNum = Math.ceil(apiRankVoList.getTotal() / apiRankVoList.getSize());
            for (ApiRankVo apiRank : apiRankVoList.getRecords()) {
                Query finalQuery = query;
                Future<ApiRankVo> future = executor.submit(() -> {
                    // 统计当日交易量
                    GatewayLogMinute gatewayLogMinute = new GatewayLogMinute();
                    gatewayLogMinute.setOpcApiCode(apiRank.getApiCode());
                    Long num = gainTodayRequestNum(gatewayLogMinute, apiRankVo.getEnv());

                    // 统计昨日交易量
                    String lastDate = "";
                    try {
                        lastDate = DateUtils.getLastDay(requestDate, 1);
                        apiRank.setRequestDate(lastDate);
                    } catch (Exception e) {
                        logger.error("获取昨日日期失败");
                    } finally {

                    }
                    String rate = "";
                    String flag = "";
                    apiRank.setEnv(apiRankVo.getEnv());
                    Long lastDayNum = gatewayLogDayService.countLastDayApiNum(apiRank);

                    if (lastDayNum.equals(0L) && num.equals(0L)) {
                        rate = "0";
                        flag = "middle";
                    } else if (lastDayNum.equals(0L) && !num.equals(0L)) {
                        rate = "100";
                        flag = "up";
                    } else {
                        DecimalFormat df = new DecimalFormat("0");//格式化小数
                        rate = df.format((float) (num - lastDayNum) / lastDayNum * 100);//返回的是String类型
                        if ("-".equals(rate.substring(0, 1))) {
                            rate = rate.replaceAll("-", "");
                            flag = "down";
                        } else {
                            flag = "up";
                        }
                    }
                    // 平均响应时间
                    DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                    double avgResTime = 0.00;
                    if (apiRank.getLineNum() != 0) {
                        avgResTime = Double.valueOf(df.format(apiRank.getResponseTime() / apiRank.getLineNum()));
                    }

                    // 成功率
                    String successRate = "0";
                    if (apiRank.getNum() != null && apiRank.getNum() != 0) {
                        double sRateD = (double) apiRank.getSuccessNum() / apiRank.getNum() * 100;
                        successRate = FormatUtils.doubleFormat(sRateD);
                    }

                    rank[0] = rank[0] + 1;
                    apiRank.setSuccessRate(successRate + "%");
                    apiRank.setResponseTime(avgResTime);
                    apiRank.setRank(rank[0] + ((finalQuery.getCurrent() - 1) * finalQuery.getSize()));
                    apiRank.setFlag(flag);
                    apiRank.setRequestDate(requestDate);
                    apiRank.setIncrease(rate + "%");

                    //统计TPS
                    String tpsDateTime = LocalDateTime.now().minusMinutes(10).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:00"));
                    apiRankVo.setTpsDateTime(tpsDateTime);
                    Double countTps = gatewayLogDayService.countTps(apiRankVo);
                    apiRank.setTps(countTps);
                    return apiRank;
                });

                futures.add(future);
            }
        }
        // 获取结果
        List<ApiRankVo> list = new ArrayList<>();
        try {
            for (int i = 0; i < futures.size(); i++) {
                list.add(futures.get(i).get());
            }
        } catch (Exception e) {
            logger.error("异常信息：", e);
        }
        apiRankVoList.setRecords(list);
        return R.data(apiRankVoList);
    }

    /**
     * @param appRankVo
     * @param query
     * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage < com.dhcc.bpm.modules.log.vo.AppRankVo>>
     * @Description 总交易量排名--渠道(应用)
     * @Author xiafayu
     * @Date 2020/2/24 15:18
     **/
    @ApiLog("总交易量排名--渠道(应用)")
    @GetMapping("/appIncrease")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "总交易量排名--渠道(应用)", notes = "传入gatewayLogDay")
    @Log(title = "总交易量排名--渠道(应用)", businessType = BusinessType.SELECT)
    public R<IPage<AppRankVo>> appIncrease(AppRankVo appRankVo, Query query) {
        // 分页为空的处理，避免设置排名报错
        if (query == null || query.getCurrent() == null || query.getSize() == null) {
            query = new Query();
            query.setCurrent(1);
            if ("workplace".equals(appRankVo.getReqFlag())) {
                query.setSize(5);
            } else if ("orderTable".equals(appRankVo.getReqFlag())) {
                query.setSize(10);
            } else {
                query.setSize(10);
            }
        }
        appRankVo.setRankFlag("true"); // 优先请求数排序
        appRankVo.setStatus(1); //  已审批
        appRankVo.setEnvStr(appRankVo.getEnv().toString());

        IPage<AppRankVo> apiRankVoList = gatewayLogDayService.countAppNum(Condition.getPage(query), appRankVo);
        Integer rank = 0;
        String requestDate = DateUtils.dateTime();
        if (apiRankVoList.getRecords() != null && apiRankVoList.getRecords().size() > 0) {
            for (AppRankVo apiRank : apiRankVoList.getRecords()) {
                GatewayLogMinute vo = new GatewayLogMinute();
                ApiRankVo apiRankVo1 = new ApiRankVo();

                vo.setEnv(appRankVo.getEnv().toString());
                if (0 == appRankVo.getEnv()) {
                    vo.setOpcAppCode(apiRank.getAppId());
                } else {
                    vo.setOpcAppCode(apiRank.getTestAppId());
                }
                Long num = gainTodayRequestNum(vo, appRankVo.getEnv().toString()); // 统计当日交易量
                String lastDate = "";
                try {
                    lastDate = DateUtils.getLastDay(requestDate, 1);
                    apiRankVo1.setRequestDate(lastDate);
                } catch (Exception e) {
                    logger.error("获取昨日日期失败");
                } finally {

                }
                String rate = "";
                String flag = "";

                // 统计昨日数据
                if (0 == appRankVo.getEnv()) {
                    apiRankVo1.setAppId(apiRank.getAppId());
                } else {
                    apiRankVo1.setAppId(apiRank.getTestAppId());
                }
                apiRankVo1.setEnv(appRankVo.getEnv().toString());
                Long lastDayNum = gatewayLogDayService.countLastDayApiNum(apiRankVo1);

                if (lastDayNum.equals(0L) && num.equals(0L)) {
                    rate = "0";
                    flag = "middle";
                } else if (lastDayNum.equals(0L) && !num.equals(0L)) {
                    rate = "100";
                    flag = "up";
                } else {
                    DecimalFormat df = new DecimalFormat("0");//格式化小数
                    rate = df.format((float) (num - lastDayNum) / lastDayNum * 100);//返回的是String类型
                    if ("-".equals(rate.substring(0, 1))) {
                        rate = rate.replaceAll("-", "");
                        flag = "down";
                    } else {
                        flag = "up";
                    }
                }
                // 平均响应时间
                DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                double avgResTime = 0.00;
                if (apiRank.getLineNum() != 0) {
                    avgResTime = Double.valueOf(df.format(apiRank.getResponseTime() / apiRank.getLineNum()));
                }

                // 成功率
                String successRate = "0";
                if (apiRank.getNum() != null && apiRank.getNum() != 0) {
                    double sRateD = (double) apiRank.getSuccessNum() / apiRank.getNum() * 100;
                    successRate = FormatUtils.doubleFormat(sRateD);
                }

                rank = rank + 1;
                apiRank.setSuccessRate(successRate + "%");
                apiRank.setResponseTime(avgResTime);
                apiRank.setRank(rank + ((query.getCurrent() - 1) * query.getSize()));
                apiRank.setFlag(flag);
                apiRank.setRequestDate(requestDate);
                apiRank.setIncrease(rate + "%");
            }
        }
        return R.data(apiRankVoList);
    }

    /**
     * @param productRankVo
     * @param query
     * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage < com.dhcc.bpm.modules.log.vo.ProductRankVo>>
     * @Description 总交易量排名--产品
     * @Author xiafayu
     * @Date 2020/2/24 15:18
     **/
    @GetMapping("/productIncrease")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "总交易量排名--产品", notes = "传入gatewayLogDay")
    @Log(title = "总交易量排名--产品", businessType = BusinessType.SELECT)
    public R<IPage<ProductRankVo>> productIncrease(ProductRankVo productRankVo, Query query) {
        // 分页为空的处理，避免设置排名报错
        if (query == null || query.getCurrent() == null || query.getSize() == null) {
            query = new Query();
            query.setCurrent(1);
            if ("workplace".equals(productRankVo.getReqFlag())) {
                query.setSize(5);
            } else if ("orderTable".equals(productRankVo.getReqFlag())) {
                query.setSize(10);
            } else {
                query.setSize(10);
            }
        }

        IPage<ProductRankVo> apiRankVoList = gatewayLogDayService.countProductNum(Condition.getPage(query), productRankVo);
        Integer rank = 0;
        String requestDate = DateUtils.dateTime();
        if (apiRankVoList.getRecords() != null && apiRankVoList.getRecords().size() > 0) {
            for (ProductRankVo apiRank : apiRankVoList.getRecords()) {
                apiRank.setId(Long.valueOf(apiRank.getProductId()));
                // 统计当日交易量
                AppApiViewVo vo = new AppApiViewVo();
                vo.setProductId(apiRank.getProductId());
                vo.setRequestDate(requestDate.substring(0, 8));
                long num = gainProductNumToday(vo, productRankVo.getEnv());

                //  获取产品昨日交易量
                String lastDate = "";
                try {
                    lastDate = DateUtils.getLastDay(requestDate, 1);
                    vo.setRequestDate(lastDate);
                } catch (Exception e) {
                    logger.error("获取昨日日期失败");
                } finally {

                }
                String rate = "";
                String flag = "";
                apiRank.setRequestDate(lastDate.substring(0, 8));
                long lastDayNum = gainProductNumOneDay(apiRank, productRankVo.getEnv());

                if (lastDayNum == 0 && num == 0) {
                    rate = "0";
                    flag = "middle";
                } else if (lastDayNum == 0 && num != 0) {
                    rate = "100";
                    flag = "up";
                } else {
                    DecimalFormat df = new DecimalFormat("0");//格式化小数
                    rate = df.format((float) (num - lastDayNum) / lastDayNum * 100);//返回的是String类型
                    if ("-".equals(rate.substring(0, 1))) {
                        rate = rate.replaceAll("-", "");
                        flag = "down";
                    } else {
                        flag = "up";
                    }
                }
                // 平均响应时间
                DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                double avgResTime = 0.00;
                if (apiRank.getLineNum() != 0) {
                    avgResTime = Double.valueOf(df.format(apiRank.getResponseTime() / apiRank.getLineNum()));
                }

                // 成功率
                String successRate = "0";
                if (apiRank.getNum() != null && apiRank.getNum() != 0) {
                    double sRateD = (double) apiRank.getSuccessNum() / apiRank.getNum() * 100;
                    successRate = FormatUtils.doubleFormat(sRateD);
                }
                rank = rank + 1;
                apiRank.setSuccessRate(successRate + "%");
                apiRank.setResponseTime(avgResTime);
                apiRank.setRank(rank + ((query.getCurrent() - 1) * query.getSize()));
                apiRank.setFlag(flag);
                apiRank.setRequestDate(requestDate);
                apiRank.setIncrease(rate + "%");
            }
        }
        return R.data(apiRankVoList);
    }

    /**
     * @param apiRankVo
     * @param query
     * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage < com.dhcc.bpm.modules.log.vo.ApiRankVo>>
     * @Description 总交易量排名--收费api
     * @Author xiafayu
     * @Date 2020/2/24 15:18
     **/
    @GetMapping("/costApiIncrease")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "总交易量排名--收费api", notes = "传入gatewayLogDay")
    @Log(title = "总交易量排名--收费API", businessType = BusinessType.SELECT)
    public R<IPage<ApiRankVo>> costApiIncrease(ApiRankVo apiRankVo, Query query) {
        // 分页为空的处理，避免设置排名报错
        if (query == null || query.getCurrent() == null || query.getSize() == null) {
            query = new Query();
            query.setCurrent(1);
            if ("workplace".equals(apiRankVo.getReqFlag())) {
                query.setSize(5);
            } else if ("orderTable".equals(apiRankVo.getReqFlag())) {
                query.setSize(10);
            } else {
                query.setSize(10);
            }
        }

        IPage<ApiRankVo> apiRankVoList = gatewayLogDayService.countCostApiNum(Condition.getPage(query), apiRankVo);
        Integer rank = 0;
        String requestDate = DateUtils.dateTime();
        if (apiRankVoList.getRecords() != null && apiRankVoList.getRecords().size() > 0) {
            for (ApiRankVo apiRank : apiRankVoList.getRecords()) {
                GatewayLogMinute gatewayLogMinute = new GatewayLogMinute();
                gatewayLogMinute.setOpcApiCode(apiRank.getApiCode());
                Long num = gainTodayRequestNum(gatewayLogMinute, apiRankVo.getEnv()); // 统计当日交易量
                String lastDate = "";
                try {
                    lastDate = DateUtils.getLastDay(requestDate, 1);
                    apiRank.setRequestDate(lastDate);
                } catch (Exception e) {
                    logger.error("获取昨日日期失败");
                } finally {

                }
                String rate = "";
                String flag = "";
                apiRank.setEnv(apiRankVo.getEnv());
                Long lastDayNum = gatewayLogDayService.countLastDayApiNum(apiRank);

                if (lastDayNum.equals(0L) && num.equals(0L)) {
                    rate = "0";
                    flag = "middle";
                } else if (lastDayNum.equals(0L) && !num.equals(0L)) {
                    rate = "100";
                    flag = "up";
                } else {
                    DecimalFormat df = new DecimalFormat("0");//格式化小数
                    rate = df.format((float) (num - lastDayNum) / lastDayNum * 100);//返回的是String类型
                    if ("-".equals(rate.substring(0, 1))) {
                        rate = rate.replaceAll("-", "");
                        flag = "down";
                    } else {
                        flag = "up";
                    }
                }

                // 平均响应时间
                DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                double avgResTime = 0.00;
                if (apiRank.getLineNum() != 0) {
                    avgResTime = Double.valueOf(df.format(apiRank.getResponseTime() / apiRank.getLineNum()));
                }

                // 成功率
                String successRate = "0";
                if (apiRank.getNum() != null && apiRank.getNum() != 0) {
                    double sRateD = (double) apiRank.getSuccessNum() / apiRank.getNum() * 100;
                    successRate = FormatUtils.doubleFormat(sRateD);
                }
                rank = rank + 1;
                apiRank.setSuccessRate(successRate + "%");
                apiRank.setResponseTime(avgResTime);
                apiRank.setRank(rank + ((query.getCurrent() - 1) * query.getSize()));
                apiRank.setFlag(flag);
                apiRank.setRequestDate(requestDate);
                apiRank.setIncrease(rate + "%");
            }
        }
        return R.data(apiRankVoList);
    }

    /**
     * @param orgaRankVo
     * @param query
     * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage < com.dhcc.bpm.modules.log.vo.OrgaRankVo>>
     * @Description 总交易量排名--机构
     * @Author xiafayu
     * @Date 2020/2/24 15:18
     **/
    @GetMapping("/orgaIncrease")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "总交易量排名--机构", notes = "传入gatewayLogDay")
    @Log(title = "总交易量排名--机构", businessType = BusinessType.SELECT)
    public R<IPage<OrgaRankVo>> orgaIncrease(OrgaRankVo orgaRankVo, Query query) {
        // 分页为空的处理，避免设置排名报错
        if (query == null || query.getCurrent() == null || query.getSize() == null) {
            query = new Query();
            query.setCurrent(1);
            if ("workplace".equals(orgaRankVo.getReqFlag())) {
                query.setSize(5);
            } else if ("orderTable".equals(orgaRankVo.getReqFlag())) {
                query.setSize(10);
            } else {
                query.setSize(10);
            }
        }

        orgaRankVo.setRankFlag("true");
        orgaRankVo.setAuthFlag("1"); // 认证状态  1--已认证
        IPage<OrgaRankVo> apiRankVoList = gatewayLogDayService.countOrgaNum(Condition.getPage(query), orgaRankVo);
        Integer rank = 0;
        String requestDate = DateUtils.dateTime();
        if (apiRankVoList.getRecords() != null && apiRankVoList.getRecords().size() > 0) {
            for (OrgaRankVo apiRank : apiRankVoList.getRecords()) {
                ApiRankVo apiRankVo1 = new ApiRankVo();
                GatewayLogMinute vo = new GatewayLogMinute();
                vo.setOpcOrgaCode(apiRank.getOpcOrgaCode());
                Long num = gainTodayRequestNum(vo, orgaRankVo.getEnv()); // 统计当日交易量
                String lastDate = "";
                try {
                    lastDate = DateUtils.getLastDay(requestDate, 1);
                    apiRankVo1.setRequestDate(lastDate);
                    apiRankVo1.setOrgaCode(apiRank.getOpcOrgaCode());
                    apiRankVo1.setEnv(orgaRankVo.getEnv());
                } catch (Exception e) {
                    logger.error("获取昨日日期失败");
                } finally {

                }
                String rate = "";
                String flag = "";

                Long lastDayNum = gatewayLogDayService.countLastDayApiNum(apiRankVo1);

                if (lastDayNum.equals(0L) && num.equals(0L)) {
                    rate = "0";
                    flag = "middle";
                } else if (lastDayNum.equals(0L) && !num.equals(0L)) {
                    rate = "100";
                    flag = "up";
                } else {
                    DecimalFormat df = new DecimalFormat("0");//格式化小数
                    rate = df.format((float) (num - lastDayNum) / lastDayNum * 100);//返回的是String类型
                    if ("-".equals(rate.substring(0, 1))) {
                        rate = rate.replaceAll("-", "");
                        flag = "down";
                    } else {
                        flag = "up";
                    }
                }

                // 平均响应时间
                DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                double avgResTime = 0.00;
                if (apiRank.getLineNum() != 0) {
                    avgResTime = Double.valueOf(df.format(apiRank.getResponseTime() / apiRank.getLineNum()));
                }

                // 成功率
                String successRate = "0";
                if (apiRank.getNum() != null && apiRank.getNum() != 0) {
                    double sRateD = (double) apiRank.getSuccessNum() / apiRank.getNum() * 100;
                    successRate = FormatUtils.doubleFormat(sRateD);
                }

                rank = rank + 1;
                apiRank.setSuccessRate(successRate + "%");
                apiRank.setResponseTime(avgResTime);
                apiRank.setRank(rank + ((query.getCurrent() - 1) * query.getSize()));
                apiRank.setFlag(flag);
                apiRank.setRequestDate(requestDate);
                apiRank.setIncrease(rate + "%");
            }
        }
        return R.data(apiRankVoList);
    }

    @PostMapping("/downlond")
    public void downlond(@RequestBody JSONObject obj, HttpServletResponse response) {

        String env = obj.getString("env");
        String reqFlag = obj.getString("reqFlag");
        String type = obj.getString("type");
        List<String> list = obj.getJSONArray("list");

        if ("api".equals(type)) {
            int page = 1;
            //创建对象
            ApiRankVo apiRankVo = new ApiRankVo();
            apiRankVo.setEnv(env);
            apiRankVo.setReqFlag(reqFlag);
            //创建对象集合
            ArrayList<ApiRankVo> apiRankVoLists = new ArrayList<>();
            while (true) {
                //自定义分页
                Query query = new Query();
                query.setCurrent(page++);
                query.setSize(10);

                //根据分页查询
                IPage<ApiRankVo> apiRankVoList = gatewayLogDayService.countApiNum(Condition.getPage(query), apiRankVo);
                Integer rank = 0;
                String requestDate = DateUtils.dateTime();
                if (apiRankVoList.getRecords() != null && apiRankVoList.getRecords().size() > 0) {
                    double maxPageNum = Math.ceil(apiRankVoList.getTotal() / apiRankVoList.getSize());
                    for (ApiRankVo apiRank : apiRankVoList.getRecords()) {
                        // 统计当日交易量
                        GatewayLogMinute gatewayLogMinute = new GatewayLogMinute();
                        gatewayLogMinute.setOpcApiCode(apiRank.getApiCode());
                        Long num = gainTodayRequestNum(gatewayLogMinute, apiRankVo.getEnv());

                        // 统计昨日交易量
                        String lastDate = "";
                        try {
                            lastDate = DateUtils.getLastDay(requestDate, 1);
                            apiRank.setRequestDate(lastDate);
                        } catch (Exception e) {
                            logger.error("获取昨日日期失败");
                        } finally {

                        }
                        String rate = "";
                        String flag = "";
                        apiRank.setEnv(apiRankVo.getEnv());
                        Long lastDayNum = gatewayLogDayService.countLastDayApiNum(apiRank);

                        if (lastDayNum.equals(0L) && num.equals(0L)) {
                            rate = "0";
                            flag = "middle";
                        } else if (lastDayNum.equals(0L) && !num.equals(0L)) {
                            rate = "100";
                            flag = "up";
                        } else {
                            DecimalFormat df = new DecimalFormat("0");//格式化小数
                            rate = df.format((float) (num - lastDayNum) / lastDayNum * 100);//返回的是String类型
                            if ("-".equals(rate.substring(0, 1))) {
                                rate = rate.replaceAll("-", "");
                                flag = "down";
                            } else {
                                flag = "up";
                            }
                        }
                        // 平均响应时间
                        DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                        double avgResTime = 0.00;
                        if (apiRank.getLineNum() != 0) {
                            avgResTime = Double.valueOf(df.format(apiRank.getResponseTime() / apiRank.getLineNum()));
                        }

                        // 成功率
                        String successRate = "0";
                        if (apiRank.getNum() != null && apiRank.getNum() != 0) {
                            double sRateD = (double) apiRank.getSuccessNum() / apiRank.getNum() * 100;
                            successRate = FormatUtils.doubleFormat(sRateD);
                        }

                        rank = rank + 1;
                        apiRank.setSuccessRate(successRate + "%");
                        apiRank.setResponseTime(avgResTime);
                        apiRank.setRank(rank + ((query.getCurrent() - 1) * query.getSize()));
                        apiRank.setFlag(flag);
                        apiRank.setRequestDate(requestDate);
                        apiRank.setIncrease(rate + "%");

                        //统计TPS
//                        String tpsDateTime = LocalDateTime.now().minusMinutes(10).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:00"));
//                        apiRankVo.setTpsDateTime(tpsDateTime);
//                        Double countTps = gatewayLogDayService.countTps(apiRankVo);
//                        apiRankVo.setTps(countTps);

                    }
                    apiRankVoLists.addAll(apiRankVoList.getRecords());
                } else {
                    break;
                }
            }
            //list的size大于0说明有条件

            ExcelUtil<ApiRankVo> util = new ExcelUtil<ApiRankVo>(ApiRankVo.class);
            util.exportSelectFileExcel(apiRankVoLists, "热门API信息表", response, list);


        } else if ("app".equals(type)) {
            int page = 1;
            AppRankVo appRankVo = new AppRankVo();
            ArrayList<AppRankVo> OrgaRankVoList = new ArrayList<>();
            appRankVo.setEnv(Long.valueOf(env));
            while (true) {
                Query query = new Query();
                query.setCurrent(page++);
                query.setSize(10);

                appRankVo.setRankFlag("true"); // 优先请求数排序
                appRankVo.setStatus(1); //  已审批
                appRankVo.setEnvStr(appRankVo.getEnv().toString());

                IPage<AppRankVo> apiRankVoList = gatewayLogDayService.countAppNum(Condition.getPage(query), appRankVo);
                Integer rank = 0;
                String requestDate = DateUtils.dateTime();
                if (apiRankVoList.getRecords() != null && apiRankVoList.getRecords().size() > 0) {
                    for (AppRankVo apiRank : apiRankVoList.getRecords()) {
                        GatewayLogMinute vo = new GatewayLogMinute();
                        ApiRankVo apiRankVo1 = new ApiRankVo();

                        vo.setEnv(appRankVo.getEnv().toString());
                        if (0 == appRankVo.getEnv()) {
                            vo.setOpcAppCode(apiRank.getAppId());
                        } else {
                            vo.setOpcAppCode(apiRank.getTestAppId());
                        }
                        Long num = gainTodayRequestNum(vo, appRankVo.getEnv().toString()); // 统计当日交易量
                        String lastDate = "";
                        try {
                            lastDate = DateUtils.getLastDay(requestDate, 1);
                            apiRankVo1.setRequestDate(lastDate);
                        } catch (Exception e) {
                            logger.error("获取昨日日期失败");
                        } finally {

                        }
                        String rate = "";
                        String flag = "";

                        // 统计昨日数据
                        if (0 == appRankVo.getEnv()) {
                            apiRankVo1.setAppId(apiRank.getAppId());
                        } else {
                            apiRankVo1.setAppId(apiRank.getTestAppId());
                        }
                        apiRankVo1.setEnv(appRankVo.getEnv().toString());
                        Long lastDayNum = gatewayLogDayService.countLastDayApiNum(apiRankVo1);

                        if (lastDayNum.equals(0L) && num.equals(0L)) {
                            rate = "0";
                            flag = "middle";
                        } else if (lastDayNum.equals(0L) && !num.equals(0L)) {
                            rate = "100";
                            flag = "up";
                        } else {
                            DecimalFormat df = new DecimalFormat("0");//格式化小数
                            rate = df.format((float) (num - lastDayNum) / lastDayNum * 100);//返回的是String类型
                            if ("-".equals(rate.substring(0, 1))) {
                                rate = rate.replaceAll("-", "");
                                flag = "down";
                            } else {
                                flag = "up";
                            }
                        }
                        // 平均响应时间
                        DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                        double avgResTime = 0.00;
                        if (apiRank.getLineNum() != 0) {
                            avgResTime = Double.valueOf(df.format(apiRank.getResponseTime() / apiRank.getLineNum()));
                        }

                        // 成功率
                        String successRate = "0";
                        if (apiRank.getNum() != null && apiRank.getNum() != 0) {
                            double sRateD = (double) apiRank.getSuccessNum() / apiRank.getNum() * 100;
                            successRate = FormatUtils.doubleFormat(sRateD);
                        }

                        rank = rank + 1;
                        apiRank.setSuccessRate(successRate + "%");
                        apiRank.setResponseTime(avgResTime);
                        apiRank.setRank(rank + ((query.getCurrent() - 1) * query.getSize()));
                        apiRank.setFlag(flag);
                        apiRank.setRequestDate(requestDate);
                        apiRank.setIncrease(rate + "%");
                    }
                    OrgaRankVoList.addAll(apiRankVoList.getRecords());
                } else {
                    break;
                }

                ExcelUtil<AppRankVo> util = new ExcelUtil<AppRankVo>(AppRankVo.class);
                util.exportSelectFileExcel(OrgaRankVoList, "渠道信息表", response, list);

            }
        } else if ("product".equals(type)) {
            int page = 1;
            ArrayList<ProductRankVo> productRankVoList = new ArrayList<>();
            ProductRankVo productRankVo = new ProductRankVo();
            productRankVo.setEnv(env);
            productRankVo.setReqFlag(reqFlag);
            while (true) {
                Query query = new Query();
                query.setCurrent(page++);
                query.setSize(10);

                IPage<ProductRankVo> apiRankVoList = gatewayLogDayService.countProductNum(Condition.getPage(query), productRankVo);
                Integer rank = 0;
                String requestDate = DateUtils.dateTime();
                if (apiRankVoList.getRecords() != null && apiRankVoList.getRecords().size() > 0) {
                    for (ProductRankVo apiRank : apiRankVoList.getRecords()) {

                        // 统计当日交易量
                        AppApiViewVo vo = new AppApiViewVo();
                        vo.setProductId(apiRank.getProductId());
                        vo.setRequestDate(requestDate);
                        long num = gainProductNumToday(vo, productRankVo.getEnv());

                        //  获取产品昨日交易量
                        String lastDate = "";
                        try {
                            lastDate = DateUtils.getLastDay(requestDate, 1);
                            vo.setRequestDate(lastDate);
                        } catch (Exception e) {
                            logger.error("获取昨日日期失败");
                        } finally {

                        }
                        String rate = "";
                        String flag = "";
                        apiRank.setRequestDate(lastDate);
                        long lastDayNum = gainProductNumOneDay(apiRank, productRankVo.getEnv());

                        if (lastDayNum == 0 && num == 0) {
                            rate = "0";
                            flag = "middle";
                        } else if (lastDayNum == 0 && num != 0) {
                            rate = "100";
                            flag = "up";
                        } else {
                            DecimalFormat df = new DecimalFormat("0");//格式化小数
                            rate = df.format((float) (num - lastDayNum) / lastDayNum * 100);//返回的是String类型
                            if ("-".equals(rate.substring(0, 1))) {
                                rate = rate.replaceAll("-", "");
                                flag = "down";
                            } else {
                                flag = "up";
                            }
                        }
                        // 平均响应时间
                        DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                        double avgResTime = 0.00;
                        if (apiRank.getLineNum() != 0) {
                            avgResTime = Double.valueOf(df.format(apiRank.getResponseTime() / apiRank.getLineNum()));
                        }

                        // 成功率
                        String successRate = "0";
                        if (apiRank.getNum() != null && apiRank.getNum() != 0) {
                            double sRateD = (double) apiRank.getSuccessNum() / apiRank.getNum() * 100;
                            successRate = FormatUtils.doubleFormat(sRateD);
                        }
                        rank = rank + 1;
                        apiRank.setSuccessRate(successRate + "%");
                        apiRank.setResponseTime(avgResTime);
                        apiRank.setRank(rank + ((query.getCurrent() - 1) * query.getSize()));
                        apiRank.setFlag(flag);
                        apiRank.setRequestDate(requestDate);
                        apiRank.setIncrease(rate + "%");
                    }

                    productRankVoList.addAll(apiRankVoList.getRecords());
                } else {
                    break;
                }

                ExcelUtil<ProductRankVo> util = new ExcelUtil<ProductRankVo>(ProductRankVo.class);
                util.exportSelectFileExcel(productRankVoList, "产品信息表", response, list);


            }
        } else if ("costApi".equals(type)) {
            int page = 1;
            ArrayList<ApiRankVo> ApiRankVoList = new ArrayList<>();
            ApiRankVo apiRankVo = new ApiRankVo();
            apiRankVo.setEnv(env);
            apiRankVo.setReqFlag(reqFlag);
            while (true) {
                Query query = new Query();
                query.setCurrent(page++);
                query.setSize(10);


                IPage<ApiRankVo> apiRankVoList = gatewayLogDayService.countCostApiNum(Condition.getPage(query), apiRankVo);
                Integer rank = 0;
                String requestDate = DateUtils.dateTime();
                if (apiRankVoList.getRecords() != null && apiRankVoList.getRecords().size() > 0) {
                    for (ApiRankVo apiRank : apiRankVoList.getRecords()) {
                        GatewayLogMinute gatewayLogMinute = new GatewayLogMinute();
                        gatewayLogMinute.setOpcApiCode(apiRank.getApiCode());
                        Long num = gainTodayRequestNum(gatewayLogMinute, apiRankVo.getEnv()); // 统计当日交易量
                        String lastDate = "";
                        try {
                            lastDate = DateUtils.getLastDay(requestDate, 1);
                            apiRank.setRequestDate(lastDate);
                        } catch (Exception e) {
                            logger.error("获取昨日日期失败");
                        } finally {

                        }
                        String rate = "";
                        String flag = "";
                        apiRank.setEnv(apiRankVo.getEnv());
                        Long lastDayNum = gatewayLogDayService.countLastDayApiNum(apiRank);

                        if (lastDayNum.equals(0L) && num.equals(0L)) {
                            rate = "0";
                            flag = "middle";
                        } else if (lastDayNum.equals(0L) && !num.equals(0L)) {
                            rate = "100";
                            flag = "up";
                        } else {
                            DecimalFormat df = new DecimalFormat("0");//格式化小数
                            rate = df.format((float) (num - lastDayNum) / lastDayNum * 100);//返回的是String类型
                            if ("-".equals(rate.substring(0, 1))) {
                                rate = rate.replaceAll("-", "");
                                flag = "down";
                            } else {
                                flag = "up";
                            }
                        }

                        // 平均响应时间
                        DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                        double avgResTime = 0.00;
                        if (apiRank.getLineNum() != 0) {
                            avgResTime = Double.valueOf(df.format(apiRank.getResponseTime() / apiRank.getLineNum()));
                        }

                        // 成功率
                        String successRate = "0";
                        if (apiRank.getNum() != null && apiRank.getNum() != 0) {
                            double sRateD = (double) apiRank.getSuccessNum() / apiRank.getNum() * 100;
                            successRate = FormatUtils.doubleFormat(sRateD);
                        }
                        rank = rank + 1;
                        apiRank.setSuccessRate(successRate + "%");
                        apiRank.setResponseTime(avgResTime);
                        apiRank.setRank(rank + ((query.getCurrent() - 1) * query.getSize()));
                        apiRank.setFlag(flag);
                        apiRank.setRequestDate(requestDate);
                        apiRank.setIncrease(rate + "%");
                    }
                    ApiRankVoList.addAll(apiRankVoList.getRecords());

                } else {
                    break;
                }

                ExcelUtil<ApiRankVo> util = new ExcelUtil<ApiRankVo>(ApiRankVo.class);
                util.exportSelectFileExcel(ApiRankVoList, "业务API息表", response, list);

            }
        } else if ("orga".equals(type)) {
            int page = 1;
            ArrayList<OrgaRankVo> OrgaRankVoList = new ArrayList<>();
            OrgaRankVo orgaRankVo = new OrgaRankVo();
            orgaRankVo.setEnv(env);
            orgaRankVo.setReqFlag(reqFlag);
            while (true) {
                Query query = new Query();
                query.setCurrent(page++);
                query.setSize(10);


                orgaRankVo.setRankFlag("true");
                orgaRankVo.setAuthFlag("1"); // 认证状态  1--已认证
                IPage<OrgaRankVo> apiRankVoList = gatewayLogDayService.countOrgaNum(Condition.getPage(query), orgaRankVo);
                Integer rank = 0;
                String requestDate = DateUtils.dateTime();
                if (apiRankVoList.getRecords() != null && apiRankVoList.getRecords().size() > 0) {
                    for (OrgaRankVo apiRank : apiRankVoList.getRecords()) {
                        ApiRankVo apiRankVo1 = new ApiRankVo();
                        GatewayLogMinute vo = new GatewayLogMinute();
                        vo.setOpcOrgaCode(apiRank.getOpcOrgaCode());
                        Long num = gainTodayRequestNum(vo, orgaRankVo.getEnv()); // 统计当日交易量
                        String lastDate = "";
                        try {
                            lastDate = DateUtils.getLastDay(requestDate, 1);
                            apiRankVo1.setRequestDate(lastDate);
                            apiRankVo1.setOrgaCode(apiRank.getOpcOrgaCode());
                            apiRankVo1.setEnv(orgaRankVo.getEnv());
                        } catch (Exception e) {
                            logger.error("获取昨日日期失败");
                        } finally {

                        }
                        String rate = "";
                        String flag = "";

                        Long lastDayNum = gatewayLogDayService.countLastDayApiNum(apiRankVo1);

                        if (lastDayNum.equals(0L) && num.equals(0L)) {
                            rate = "0";
                            flag = "middle";
                        } else if (lastDayNum.equals(0L) && !num.equals(0L)) {
                            rate = "100";
                            flag = "up";
                        } else {
                            DecimalFormat df = new DecimalFormat("0");//格式化小数
                            rate = df.format((float) (num - lastDayNum) / lastDayNum * 100);//返回的是String类型
                            if ("-".equals(rate.substring(0, 1))) {
                                rate = rate.replaceAll("-", "");
                                flag = "down";
                            } else {
                                flag = "up";
                            }
                        }

                        // 平均响应时间
                        DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                        double avgResTime = 0.00;
                        if (apiRank.getLineNum() != 0) {
                            avgResTime = Double.valueOf(df.format(apiRank.getResponseTime() / apiRank.getLineNum()));
                        }

                        // 成功率
                        String successRate = "0";
                        if (apiRank.getNum() != null && apiRank.getNum() != 0) {
                            double sRateD = (double) apiRank.getSuccessNum() / apiRank.getNum() * 100;
                            successRate = FormatUtils.doubleFormat(sRateD);
                        }

                        rank = rank + 1;
                        apiRank.setSuccessRate(successRate + "%");
                        apiRank.setResponseTime(avgResTime);
                        apiRank.setRank(rank + ((query.getCurrent() - 1) * query.getSize()));
                        apiRank.setFlag(flag);
                        apiRank.setRequestDate(requestDate);
                        apiRank.setIncrease(rate + "%");
                    }
                    OrgaRankVoList.addAll(apiRankVoList.getRecords());

                } else {
                    break;
                }
                ExcelUtil<OrgaRankVo> util = new ExcelUtil<OrgaRankVo>(OrgaRankVo.class);
                util.exportSelectFileExcel(OrgaRankVoList, "机构信息表", response, list);

            }
        }


    }

    /**
     * @param type
     * @Description api统计响应时间趋势
     * @Author wjh
     * @Date 2020-10-26 15:24:52
     **/
    @GetMapping("/timeApiTrends/{type}")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "api统计响应时间趋势")
    @Log(title = "api统计响应时间趋势", businessType = BusinessType.SELECT)
    public R<List<TradeTrendsVo>> tradingATimeTrends(@PathVariable("type") String type, GatewayLogDayVO gatewayLogDayVO) throws Exception {
        String nowDate = DateUtils.dateTime();
        String flag = "";
        List<TradeVolumnVo> tradeTrendsLists = new LinkedList<>();
        List<TradeTrendsVo> tradeVoListData = new LinkedList<>();
        // 本部门API列表
        Query query = new Query();
        query.setCurrent(1);
        query.setSize(999999999); // 不分页
        ApiVO api = new ApiVO();
        List<Long> ids = new ArrayList<>();
        if (gatewayLogDayVO.getApiId() != null) {
            //api发布页面传进来
            ids.add(gatewayLogDayVO.getApiId());
            api.setApiIds(ids);
        }
        if (gatewayLogDayVO.getBaseProductId() != null) {
            //基础产品页面传进来
            List<Long> listNew = getBaseProductList(gatewayLogDayVO.getBaseProductId());
            api.setApiIds(listNew);
        }
        if (gatewayLogDayVO.getProductId() != null) {
            //应用产品页面传进来
            List<Long> apiIds = apiService.getProdApiIdsByProductId(gatewayLogDayVO.getProductId());
            api.setApiIds(apiIds);
        }

        if (gatewayLogDayVO.getOpcSysId() != null) {
            //系统页面传进来----系统id，找到基础产品id，在找到api的id
            List<BaseProduct> baseProductList = baseProductService.selectBySysId(gatewayLogDayVO.getOpcSysId());
            for (BaseProduct baseProduct : baseProductList) {
                List<Long> listNew = getBaseProductList(baseProduct.getId());
                ids.addAll(listNew);
            }
            api.setApiIds(ids);
        }
        IPage<ApiVO> page = apiService.listInfo(Condition.getPage(query), api); // 查当前登录部门API列表信息
        Set<String> apiCodeSet = new HashSet<>();
        if (page.getRecords() != null && page.getRecords().size() > 0) {
            for (ApiVO apiVO : page.getRecords()) {
                if (apiVO.getApiCode() != null) {
                    apiCodeSet.add(apiVO.getApiCode());
                }
            }
        }
        List<String> apiCodeList = new ArrayList<>();
        Iterator<String> it = apiCodeSet.iterator();
        while (it.hasNext()) {
            apiCodeList.add(it.next());
        }
        gatewayLogDayVO.setApiCodeList(apiCodeList);
        switch (type) {
            case "day":
                String[] dateArr = DateUtils.getDateTimeAddOneHour(-24);//获取到24小时前时间和现在时间
                List<String> dayTicks = new ArrayList<>();
                String temp = dateArr[0];//开始时间
                dayTicks.add(temp.substring(0, 12));//MMddHHmm
                while (temp.compareTo(dateArr[1]) < 0) {
                    //时间加2小时
                    String addDate = DateUtils.getAddTenMinute(temp, 7200000);
                    dayTicks.add(addDate.substring(0, 12));//MMddHHmm
                    temp = addDate;
                }
                GatewayLogMinuteVO gatewayLogMinuteVO = new GatewayLogMinuteVO();
                if (!StringUtils.isEmpty(gatewayLogDayVO.getEnv())) {
                    gatewayLogMinuteVO.setEnv(gatewayLogDayVO.getEnv());
                }

                gatewayLogMinuteVO.setApiCodeList(apiCodeList);
                gatewayLogMinuteVO.setStartDate(dateArr[0]);//开始时间
                gatewayLogMinuteVO.setEndDate(dateArr[1]);//结束时间

                List<FutureTask> futureTasks = new ArrayList<>();
                for (int i = 0; i < 3; i++) {
                    int finalI = i;
                    FutureTask futureTask = new FutureTask(() -> {
                        Query query1 = new Query();
                        query1.setCurrent(finalI + 1);
                        query1.setSize(500);
                        gatewayLogMinuteVO.setPage(finalI + 1);
                        gatewayLogMinuteVO.setSize(500);
                        List<TradeVolumnVo> page1 = gatewayLogMinuteService.countGatewayLogMinuteByDate(gatewayLogMinuteVO);
                        return page1;
                    });
                    futureTask.run();
                    futureTasks.add(futureTask);
                }
                for (FutureTask<List<TradeVolumnVo>> futureTask : futureTasks) {
                    try {
                        tradeTrendsLists.addAll(futureTask.get());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                }

                tradeVoListData = getTenMinuteTimeData(dateArr, tradeTrendsLists);

                break;
            case "week":
//                flag = "week";
//                tradeVoListData = tradingTrendsWM(flag, gatewayLogDayVO, nowDate);    // 获取周交易趋势

                String[] dateArr2 = new String[2];
                dateArr2[0] = DateUtils.dateTime().substring(0, 12) + "00";
                dateArr2[1] = DateUtils.getPastDate(-6, "yyyyMMddHHmmss").substring(0, 12) + "00";//一周前的日期

                GatewayLogMinuteVO gatewayLogMinuteVO2 = new GatewayLogMinuteVO();
                if (!StringUtils.isEmpty(gatewayLogDayVO.getEnv())) {
                    gatewayLogMinuteVO2.setEnv(gatewayLogDayVO.getEnv());
                }

                gatewayLogMinuteVO2.setApiCodeList(apiCodeList);
                gatewayLogMinuteVO2.setStartDate(dateArr2[1]);//开始时间
                gatewayLogMinuteVO2.setEndDate(dateArr2[0]);//结束时间

                List<FutureTask> futureTasks2 = new ArrayList<>();
                for (int i = 0; i < 3; i++) {
                    int finalI = i;
                    FutureTask futureTask = new FutureTask(() -> {
                        Query query1 = new Query();
                        query1.setCurrent(finalI + 1);
                        query1.setSize(1200);
                        gatewayLogMinuteVO2.setPage(finalI + 1);
                        gatewayLogMinuteVO2.setSize(1200);
                        List<TradeVolumnVo> page1 = gatewayLogMinuteService.countGatewayLogMinuteByDate(gatewayLogMinuteVO2);
                        return page1;
                    });
                    futureTask.run();
                    futureTasks2.add(futureTask);
                }
                for (FutureTask<List<TradeVolumnVo>> futureTask : futureTasks2) {
                    try {
                        tradeTrendsLists.addAll(futureTask.get());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                }

                tradeVoListData = getWeekTimeData(dateArr2, tradeTrendsLists);

                break;
            case "month":
//                tradeVoListData = tradingTrendsWM(flag, gatewayLogDayVO, nowDate); // 获取月交易趋势

                String[] dateArr3 = new String[2];
                dateArr3[0] = DateUtils.dateTime();
                dateArr3[1] = DateUtils.getLastDay(dateArr3[0], 29) + "000000";//一周前的日期

                GatewayLogMinuteVO gatewayLogMinuteVO3 = new GatewayLogMinuteVO();
                if (!StringUtils.isEmpty(gatewayLogDayVO.getEnv())) {
                    gatewayLogMinuteVO3.setEnv(gatewayLogDayVO.getEnv());
                }

                gatewayLogMinuteVO3.setApiCodeList(apiCodeList);
                gatewayLogMinuteVO3.setStartDate(dateArr3[1]);//开始时间
                gatewayLogMinuteVO3.setEndDate(dateArr3[0]);//结束时间

                List<FutureTask> futureTasks3 = new ArrayList<>();
                for (int i = 0; i < 3; i++) {
                    int finalI = i;
                    FutureTask futureTask = new FutureTask(() -> {
                        Query query1 = new Query();
                        query1.setCurrent(finalI + 1);
                        query1.setSize(3500);
                        gatewayLogMinuteVO3.setPage(finalI + 1);
                        gatewayLogMinuteVO3.setSize(3500);
                        List<TradeVolumnVo> page1 = gatewayLogMinuteService.countGatewayLogMinuteByDate(gatewayLogMinuteVO3);
                        return page1;
                    });
                    futureTask.run();
                    futureTasks3.add(futureTask);
                }
                for (FutureTask<List<TradeVolumnVo>> futureTask : futureTasks3) {
                    try {
                        tradeTrendsLists.addAll(futureTask.get());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                }
                tradeVoListData = getMonthTimeData(dateArr3, tradeTrendsLists);

                break;
            case "year":
                /*String beginDate = nowDate.substring(0, 4) + "0101";
                String endDate = nowDate.substring(0, 4) + "1231";
                gatewayLogDayVO.setBeginDate(beginDate);
                gatewayLogDayVO.setEndDate(endDate);
                List<TradeTrendsVo> tradeVoLists = gatewayLogDayService.countNumByYear(gatewayLogDayVO);
                Map<String, Integer> mapYear = new LinkedHashMap<String, Integer>(); // 返回
                for (int i = 1; i <= 12; i++) {
                    mapYear.put(String.valueOf(i), 0);
                }
                for (String key : mapYear.keySet()) {
                    TradeTrendsVo tradeTrends = new TradeTrendsVo();
                    tradeTrends.setRequestTime(key + "月");
                    if (tradeVoLists != null && tradeVoLists.size() > 0) {
                        for (TradeTrendsVo tradeTrendsVo : tradeVoLists) {
                            tradeTrendsVo.setRequestTime(String.valueOf(Integer.parseInt(tradeTrendsVo.getRequestTime())));
                            if (key.equals(tradeTrendsVo.getRequestTime())) {
                                tradeTrends.setRequestConsume(tradeTrendsVo.getRequestConsume());
                                break;
                            }
                        }
                    }
                    tradeVoListData.add(tradeTrends);
                }*/

                String beginDate = nowDate.substring(0, 4) + "0101";
                String endDate = nowDate.substring(0, 4) + "1231";

                GatewayLogDayVO logDayVO = new GatewayLogDayVO();
                if (!StringUtils.isEmpty(gatewayLogDayVO.getEnv())) {
                    logDayVO.setEnv(gatewayLogDayVO.getEnv());
                }
                logDayVO.setApiCodeList(apiCodeList);
                logDayVO.setBeginDate(beginDate);//开始时间
                logDayVO.setEndDate(endDate);//结束时间
                List<TradeTrendsVo> trendsVoList = gatewayLogDayService.countNumBydate(logDayVO);
                tradeVoListData = getYearTime365Data(nowDate.substring(0, 4), trendsVoList);

                break;
            default:
                break;
        }
        // 整理给前台返回格式
        List<TradeTrendsVo> resList = new ArrayList<>();
        long totalTime = 0L;
        double averageTime = 0D;
        Set<Long> set = new TreeSet<>();//有自动排序
        if (tradeVoListData != null && tradeVoListData.size() > 0) {
            for (int i = 0; i < tradeVoListData.size(); i++) {
                TradeTrendsVo vo = tradeVoListData.get(i);
                if (vo != null && (vo.getRequestConsume() == null || "".equals(vo.getRequestConsume()))) {
                    vo.setRequestConsume("0");
                }
                if (vo != null) {
                    // 本日数据重新赋值(周、月) 年忽略本日数据
                    //日类型数据进入 修改时间：20201201
                    if ("day".equals(type) && vo.getRequestTime().equals(nowDate)) {
                        GatewayLogMinute gatewayLogMinute = new GatewayLogMinute();
                        gatewayLogMinute.setRequestDate(nowDate);
                        gatewayLogMinute.setEnv(gatewayLogDayVO.getEnv());
                        TradeVolumnVo tradeVolumnVo = gatewayLogMinuteService.tradingVolume(gatewayLogMinute);
                        if (tradeVolumnVo == null || tradeVolumnVo.getRequestConsume() == null || "".equals(tradeVolumnVo.getRequestConsume())) {
                            vo.setRequestConsume("0");
                        } else {
                            vo.setRequestConsume(tradeVolumnVo.getRequestConsume().toString());
                        }

                        totalTime += Long.valueOf(vo.getRequestConsume());
                        set.add(Long.valueOf(vo.getRequestConsume()));//添加，为了排序
                    }

                    TradeTrendsVo tradeTrendsVo = new TradeTrendsVo();
                    if (i == tradeVoListData.size() - 1) {
                        //最后一条
                        averageTime = (double) (totalTime / Long.valueOf(tradeVoListData.size()));
                        DecimalFormat format = new DecimalFormat("0.00");
                        String result = format.format(averageTime);
                        tradeTrendsVo.setAverageConsume(result);

                        Object[] setarry = set.toArray();//转数组，为了获取最后一个元素，即最大元素
                        //修改数组为空时数组越界异常  xiafayu 20201120 09:16:11
                        if (setarry.length > 0) {
                            tradeTrendsVo.setMaxConsume(setarry[setarry.length - 1].toString());
                        }
                    }
                    tradeTrendsVo.setRequestTime(vo.getRequestTime());
                    tradeTrendsVo.setRequestConsume(vo.getRequestConsume());
                    tradeTrendsVo.setType("响应时间");
                    resList.add(tradeTrendsVo);
                }
            }
        }
        return R.data(resList);
    }

    /**
     * @param type
     * @param gatewayLogDayVO
     * @return
     * @Description 首页交易趋势
     * @Author xiafayu
     * @Date 2020/2/24 15:19
     **/
    @GetMapping("/tradingTrends/{type}")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "首页交易趋势")
    @Log(title = "交易趋势", businessType = BusinessType.SELECT)
    public R<List<TradeTrendsVo>> tradingTrends(@PathVariable("type") String type, GatewayLogDayVO gatewayLogDayVO) throws Exception {
        List<TradeVolumnVo> tradeTrendsLists = new Vector<>();
        String nowDate = DateUtils.dateTime();
        List<TradeTrendsVo> tradeVoListData = new LinkedList<>();
        String flag = "";
        String[] date = DateUtils.getDateTimeAddOneHour(-1);
        String[] dateArr = DateUtils.getDateTimeAddOneHour(-24);//获取到24小时前时间和现在时间
        List<String> dayTicks = new ArrayList<>();
        // 本部门API列表
        Query query = new Query();
        query.setCurrent(1);
        query.setSize(999999999); // 不分页
        ApiVO api = new ApiVO();
        List<Long> ids = new ArrayList<>();
        if (gatewayLogDayVO.getApiId() != null) {
            //api发布页面传进来
            ids.add(gatewayLogDayVO.getApiId());
            api.setApiIds(ids);
        }
        if (gatewayLogDayVO.getBaseProductId() != null) {
            //基础产品页面传进来
            List<Long> listNew = getBaseProductList(gatewayLogDayVO.getBaseProductId());

            api.setApiIds(listNew);
        }
        if (gatewayLogDayVO.getProductId() != null) {
            //应用产品页面传进来
            List<Long> apiIds = apiService.getProdApiIdsByProductId(gatewayLogDayVO.getProductId());

            api.setApiIds(apiIds);
        }
        if (gatewayLogDayVO.getOpcSysId() != null) {
            //系统页面传进来----系统id，找到基础产品id，在找到api的id
            List<Long> apiIds = apiService.getApiIdsBySysId(String.valueOf(gatewayLogDayVO.getOpcSysId()));
            api.setApiIds(apiIds);
        }

        IPage<ApiVO> page = apiService.listInfo(Condition.getPage(query), api); // 查当前登录部门API列表信息
        List<String> apiCodeList = new ArrayList<>();
        if (page.getRecords() != null && page.getRecords().size() > 0) {
            for (ApiVO apiVO : page.getRecords()) {
                apiCodeList.add(apiVO.getApiCode());
            }
        }
        gatewayLogDayVO.setApiCodeList(apiCodeList);

        switch (type) {
            case "day":
                String temp = dateArr[0];//开始时间
                dayTicks.add(temp.substring(0, 12));//MMddHHmm
                while (temp.compareTo(dateArr[1]) < 0) {
                    //时间加2小时
                    String addDate = DateUtils.getAddTenMinute(temp, 7200000);
                    dayTicks.add(addDate.substring(0, 12));//MMddHHmm
                    temp = addDate;
                }
                GatewayLogMinuteVO gatewayLogMinuteVO = new GatewayLogMinuteVO();
                if (!StringUtils.isEmpty(gatewayLogDayVO.getEnv())) {
                    gatewayLogMinuteVO.setEnv(gatewayLogDayVO.getEnv());
                }

                gatewayLogMinuteVO.setApiCodeList(apiCodeList);
                gatewayLogMinuteVO.setStartDate(dateArr[0]);//开始时间
                gatewayLogMinuteVO.setEndDate(dateArr[1]);//结束时间

                List<FutureTask> futureTasks = new ArrayList<>();
                for (int i = 0; i < 1; i++) {
                    int finalI = i;
                    FutureTask futureTask = new FutureTask(() -> {
                        Query query1 = new Query();
                        query1.setCurrent(finalI + 1);
                        query1.setSize(50000);
                        gatewayLogMinuteVO.setPage(finalI + 1);
                        gatewayLogMinuteVO.setSize(50000);
                        List<TradeVolumnVo> page1 = gatewayLogMinuteService.countGatewayLogMinuteByTime(gatewayLogMinuteVO);
                        System.out.println(finalI + 1);
                        System.out.println(page1);
                        return page1;
                    });
                    futureTask.run();
                    futureTasks.add(futureTask);
                }
                for (FutureTask<List<TradeVolumnVo>> futureTask : futureTasks) {
                    try {
                        tradeTrendsLists.addAll(futureTask.get());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                }

                tradeVoListData = getTenMinuteData(dateArr, tradeTrendsLists);
//                GatewayLogMinuteVO gatewayLogMinuteVO = new GatewayLogMinuteVO();
//                gatewayLogMinuteVO.setRequestDate(nowDate);
//                if (!StringUtils.isEmpty(gatewayLogDayVO.getEnv())) {
//                    gatewayLogMinuteVO.setEnv(gatewayLogDayVO.getEnv());
//                }
//                gatewayLogMinuteVO.setApiCodeList(apiCodeList);
//                tradeTrendsLists = gatewayLogMinuteService.countGatewayLogMinuteByDate(gatewayLogMinuteVO);
//                Map<Integer, Long> mapDay = new LinkedHashMap<Integer, Long>();
//
//                Map<Integer, Long> sucNumMap = new LinkedHashMap<Integer, Long>();
//                for (int i = 0; i < 12; i++) {
//                    mapDay.put(i * 2, 0L);
//                    sucNumMap.put(i * 2, 0L);
//                }
//                Map<Integer, Long> failNumMap = new LinkedHashMap<Integer, Long>();
//                for (int i = 0; i < 12; i++) {
//                    failNumMap.put(i * 2, 0L);
//                }
//                if (tradeTrendsLists != null && tradeTrendsLists.size() > 0) {
//                    for (TradeVolumnVo tradeVolumnVo : tradeTrendsLists) {
//                        long num = tradeVolumnVo.getNum();
//                        int hour = (int) Math.floor(Integer.valueOf(tradeVolumnVo.getRequestTime()) / 2);
//                        mapDay.put(hour * 2, mapDay.get(hour * 2) + num);
//
//                        long sucNum = tradeVolumnVo.getSuccessNum();
//                        sucNumMap.put(hour * 2, sucNumMap.get(hour * 2) + sucNum);
//                        //-----add 失败交易数------------2020-10-14 14:39:10----------------
//                        long failNum = tradeVolumnVo.getFail();
//                        failNumMap.put(hour * 2, failNumMap.get(hour * 2) + failNum);
//
//                    }
//                }
//
//                for (Integer hour : mapDay.keySet()) {
//                    TradeTrendsVo tradeTrendsVo = new TradeTrendsVo();
//                    Long num = mapDay.get(hour);
//                    tradeTrendsVo.setRequestTime(hour + ":00");
//                    tradeTrendsVo.setNum(num);
//
//                    Long sucNum = sucNumMap.get(hour);
//                    tradeTrendsVo.setSuccessNum(sucNum);
//
//                    Long failNum = failNumMap.get(hour);
//                    tradeTrendsVo.setFailNum(failNum);
//
//                    tradeVoListData.add(tradeTrendsVo);
//                }
                break;
            case "hour":
                GatewayLogMinuteVO gatewayLogMinuteVO2 = new GatewayLogMinuteVO();
                if (!StringUtils.isEmpty(gatewayLogDayVO.getEnv())) {
                    gatewayLogMinuteVO2.setEnv(gatewayLogDayVO.getEnv());
                }
                gatewayLogMinuteVO2.setApiCodeList(apiCodeList);
                gatewayLogMinuteVO2.setStartDate(date[0]);//开始时间
                gatewayLogMinuteVO2.setEndDate(date[1]);//结束时间
                tradeTrendsLists = gatewayLogMinuteService.countGatewayLogMinuteByDateHour(gatewayLogMinuteVO2);
                tradeVoListData = getHourData(date, tradeTrendsLists);
                break;
            case "week":
//                flag = "week";
//                tradeVoListData = tradingTrendsWM(flag, gatewayLogDayVO, nowDate);    // 获取周交易趋势


                String[] dateArr2 = new String[2];
                dateArr2[0] = DateUtils.dateTime().substring(0, 12) + "00";
                dateArr2[1] = DateUtils.getPastDate(-6, "yyyyMMddHHmmss").substring(0, 12) + "00";//一周前的日期

                GatewayLogMinuteVO logMinuteVO = new GatewayLogMinuteVO();
                if (!StringUtils.isEmpty(gatewayLogDayVO.getEnv())) {
                    logMinuteVO.setEnv(gatewayLogDayVO.getEnv());
                }

                logMinuteVO.setApiCodeList(apiCodeList);
                logMinuteVO.setStartDate(dateArr2[1]);//开始时间
                logMinuteVO.setEndDate(dateArr2[0]);//结束时间

                List<FutureTask> futureTasks2 = new ArrayList<>();
                for (int i = 0; i < 1; i++) {
                    int finalI = i;
                    FutureTask futureTask = new FutureTask(() -> {
                        Query query1 = new Query();
                        query1.setCurrent(finalI + 1);
                        query1.setSize(100000);
                        logMinuteVO.setPage(finalI + 1);
                        logMinuteVO.setSize(100000);
                        List<TradeVolumnVo> page1 = gatewayLogMinuteService.countGatewayLogMinuteByTime(logMinuteVO);
                        System.out.println(finalI + 1);
                        System.out.println(page1);
                        return page1;
                    });
                    futureTask.run();
                    futureTasks2.add(futureTask);
                }
                for (FutureTask<List<TradeVolumnVo>> futureTask : futureTasks2) {
                    try {
                        tradeTrendsLists.addAll(futureTask.get());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                }

                tradeVoListData = getTwoHoursData(dateArr2, tradeTrendsLists);
                break;
            case "month":
//                tradeVoListData = tradingTrendsWM(flag, gatewayLogDayVO, nowDate); // 获取月交易趋势
                String[] dateArrM = new String[2];
                String nowDate222 = DateUtils.dateTime().substring(0, 12) + "00";
                String endDate = "";
                if (Integer.valueOf(nowDate222.substring(8, 10)) >= 12) {
                    dateArrM[0] = nowDate222.substring(0, 8) + "120000";
                    endDate = nowDate222.substring(0, 8) + "235959";  //最后一个点是12点实际计算的是 12-23.59的数
                } else {
                    dateArrM[0] = nowDate222.substring(0, 8) + "000000";
                    endDate = dateArrM[0];
                }

                dateArrM[1] = DateUtils.getLastDay(dateArrM[0], 29) + dateArrM[0].substring(8);//一月前的日期

                GatewayLogMinuteVO logMinuteVO1 = new GatewayLogMinuteVO();
                if (!StringUtils.isEmpty(gatewayLogDayVO.getEnv())) {
                    logMinuteVO1.setEnv(gatewayLogDayVO.getEnv());
                }

                logMinuteVO1.setApiCodeList(apiCodeList);
                logMinuteVO1.setStartDate(dateArrM[1]);//开始时间
                logMinuteVO1.setEndDate(endDate);//结束时间

                List<FutureTask> futureTasks3 = new ArrayList<>();
                for (int i = 0; i < 3; i++) {
                    int finalI = i;
                    FutureTask futureTask = new FutureTask(() -> {
                        Query query1 = new Query();
                        query1.setCurrent(finalI + 1);
                        query1.setSize(10000);
                        logMinuteVO1.setPage(finalI + 1);
                        logMinuteVO1.setSize(50000);
                        List<TradeVolumnVo> page1 = gatewayLogMinuteService.countGatewayLogMinuteByTime(logMinuteVO1);
                        System.out.println(finalI + 1);
                        System.out.println(page1);
                        return page1;
                    });
                    futureTask.run();
                    futureTasks3.add(futureTask);
                }
                for (FutureTask<List<TradeVolumnVo>> futureTask : futureTasks3) {
                    try {
                        tradeTrendsLists.addAll(futureTask.get());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                }

                tradeVoListData = getMonthsData(dateArrM, tradeTrendsLists);

                break;
            case "year":
                String beginDate = nowDate.substring(0, 4) + "0101";
                String endDate2 = nowDate.substring(0, 4) + "1231";
                gatewayLogDayVO.setBeginDate(beginDate);
                gatewayLogDayVO.setEndDate(endDate2);
                List<TradeTrendsVo> trendsVoListYear = gatewayLogDayService.countNumBydate(gatewayLogDayVO);
                tradeVoListData = getYearsData365(nowDate.substring(0, 4), trendsVoListYear);
//                List<TradeTrendsVo> tradeVoLists = gatewayLogDayService.countNumByYear(gatewayLogDayVO);
/*                Map<String, Integer> mapYear = new LinkedHashMap<String, Integer>(); // 返回
                for (int i = 1; i <= 12; i++) {
                    mapYear.put(String.valueOf(i), 0);
                }
                for (String key : mapYear.keySet()) {
                    TradeTrendsVo tradeTrends = new TradeTrendsVo();
                    tradeTrends.setRequestTime(key + "月");
                    tradeTrends.setNum(0L);
                    tradeTrends.setSuccessNum(0L);
                    tradeTrends.setFailNum(0L);
                    if (tradeVoLists != null && tradeVoLists.size() > 0) {
                        for (TradeTrendsVo tradeTrendsVo : tradeVoLists) {
                            tradeTrendsVo.setRequestTime(String.valueOf(Integer.parseInt(tradeTrendsVo.getRequestTime())));
                            if (key.equals(tradeTrendsVo.getRequestTime())) {
                                tradeTrends.setNum(tradeTrendsVo.getNum());
                                tradeTrends.setSuccessNum(tradeTrendsVo.getSuccessNum());
                                tradeTrends.setFailNum(tradeTrendsVo.getFailNum());
                                tradeTrends.setRequestConsume(tradeTrendsVo.getRequestConsume());
                                break;
                            }
                        }
                    }
                    tradeVoListData.add(tradeTrends);
                }*/
                break;
            default:
                break;
        }
        // 整理给前台返回格式
        List<TradeTrendsVo> resList = new ArrayList<TradeTrendsVo>();
        if (tradeVoListData != null && tradeVoListData.size() > 0) {
            List<String> ticks = new ArrayList<>();
            for (TradeTrendsVo vo : tradeVoListData) {
                // 本日数据重新赋值(周、月) 年忽略本日数据
                if ("day".equals(type) && vo.getRequestTime().equals(nowDate)) {
                    GatewayLogMinute gatewayLogMinute = new GatewayLogMinute();
                    gatewayLogMinute.setRequestDate(nowDate);
                    gatewayLogMinute.setEnv(gatewayLogDayVO.getEnv());
                    TradeVolumnVo tradeVolumnVo = gatewayLogMinuteService.tradingVolume(gatewayLogMinute);
                    if (tradeVolumnVo == null) {
                        vo.setNum(0L);
                        vo.setSuccessNum(0L);
                        vo.setFailNum(0L);
                        vo.setResponseNum(0L);
                    } else {
                        vo.setNum(tradeVolumnVo.getNum());
                        vo.setSuccessNum(tradeVolumnVo.getSuccessNum());
                        vo.setFailNum(tradeVolumnVo.getFail());
                        vo.setResponseNum(tradeVolumnVo.getResponseNum());
                    }

                }


                TradeTrendsVo tradeTrendsVo = new TradeTrendsVo();

                if ("day".equals(type)) {
                    tradeTrendsVo.setTicks(dayTicks);
                } else if ("hour".equals(type)) {
                    String temp2 = date[0];//开始时间
                    List<String> ticks3 = new ArrayList<>();
                    ticks3.add(DateUtils.getDateHHmmss(temp2));
                    while (temp2.compareTo(date[1]) < 0) {
                        //时间加10min
                        String addDate = DateUtils.getAddTenMinute(temp2, 600000);
                        ticks3.add(DateUtils.getDateHHmmss(addDate));//去掉年月日
                        temp2 = addDate;
                    }
                    tradeTrendsVo.setTicks(ticks3);
                } else {
                    ticks.add(vo.getRequestTime());
                }
                if (!"day".equals(type) && !"hour".equals(type)) {
                    tradeTrendsVo.setTicks(ticks);
                }

                if ("hour".equals(type)) {
                    tradeTrendsVo.setRequestTime(DateUtils.getDateHHmmss(vo.getRequestTime()));
                } else {
                    tradeTrendsVo.setRequestTime(vo.getRequestTime());
                }

                if (vo.getFailNum() + vo.getSuccessNum() == 0L) {
                    tradeTrendsVo.setSuccessRate(1);
                    tradeTrendsVo.setResponseRate(1);
                } else {
                    Double suc = (double) vo.getSuccessNum() / (double) (vo.getFailNum() + vo.getSuccessNum());
                    Double res = (double) vo.getResponseNum() / (double) (vo.getFailNum() + vo.getSuccessNum());
                    //计算成功率
                    tradeTrendsVo.setSuccessRate(suc == 0.0 ? 1 : suc);
                    //计算响应率
                    tradeTrendsVo.setResponseRate(res == 0.0 ? 1 : res);
                }

                tradeTrendsVo.setNum(vo.getFailNum() + vo.getSuccessNum());
                tradeTrendsVo.setSuccessNum(vo.getSuccessNum());
                tradeTrendsVo.setFailNum(vo.getFailNum());
                tradeTrendsVo.setResponseNum(vo.getResponseNum());
                tradeTrendsVo.setType("交易成功数");
                resList.add(tradeTrendsVo);
//                TradeTrendsVo tradeTrendsVo1 = new TradeTrendsVo();
//                if ("hour".equals(type)){
//                    tradeTrendsVo1.setRequestTime(DateUtils.getDateHHmmss(vo.getRequestTime()));
//                }else {
//                    tradeTrendsVo1.setRequestTime(vo.getRequestTime());
//                }
//
//                tradeTrendsVo1.setNum(vo.getSuccessNum());
//                tradeTrendsVo1.setType("交易成功数");
//                resList.add(tradeTrendsVo1);


                //--------2020-10-26 16:48:12 wjh新加需求---------start-------------
                TradeTrendsVo tradeTrendsVo2 = new TradeTrendsVo();
                if ("hour".equals(type)) {
                    tradeTrendsVo2.setRequestTime(DateUtils.getDateHHmmss(vo.getRequestTime()));
                } else {
                    tradeTrendsVo2.setRequestTime(vo.getRequestTime());
                }
                if (vo.getFailNum() + vo.getSuccessNum() == 0L) {
                    tradeTrendsVo2.setSuccessRate(1);
                    tradeTrendsVo2.setResponseRate(1);
                } else {
                    Double suc = (double) vo.getSuccessNum() / (double) (vo.getFailNum() + vo.getSuccessNum());
                    Double res = (double) vo.getResponseNum() / (double) (vo.getFailNum() + vo.getSuccessNum());
                    //计算成功率
                    tradeTrendsVo2.setSuccessRate(suc == 0.0 ? 1 : suc);
                    //计算响应率
                    tradeTrendsVo2.setResponseRate(res == 0.0 ? 1 : res);
                }

                tradeTrendsVo2.setNum(vo.getFailNum());
                tradeTrendsVo2.setType("交易失败数");
                resList.add(tradeTrendsVo2);
                //--------------end------------------------------------------------

            }
        }
        return R.data(resList);
    }

    /**
     * @Author wangjinghan
     * @Description 一年 每天一个点
     * @date: 2022年3月2日16:49:43
     */
    private List<TradeTrendsVo> getYearTime365Data(String year, List<TradeTrendsVo> tradeTrendsLists) {
        int yearDay = Integer.valueOf(year);  //获取当年 天数
        boolean isRun = false;  //是否是闰年
        if (yearDay % 4 == 0 && yearDay % 100 != 0 || yearDay % 400 == 0) {
            isRun = true;
        }
        List<TradeTrendsVo> oneYearList = new ArrayList<>(isRun ? 366 : 355);
        for (int i = 1; i <= 12; i++) {
            for (int y = 1; y <= 31; y++) {
                if (y == 29 && i == 2 && !isRun) {
                    //不是闰年
                    break;
                }
                if (y > 29 && i == 2) {
                    break;
                }

                if (y == 31 && (i == 4 || i == 6 || i == 9 || i == 11)) {
                    //共30天
                    break;
                }
                String requestTime = "";
                if (i >= 10 && y >= 10) {
                    requestTime = year + i + y;
                } else if (i < 10 && y >= 10) {
                    requestTime = year + "0" + i + y;
                } else {
                    requestTime = year + "0" + i + "0" + y;
                }
                String finalRequestTime = requestTime;
                Optional<TradeTrendsVo> trendsVoOptional = tradeTrendsLists.stream().filter(item -> finalRequestTime.equals(item.getRequestTime())).findFirst();
                if (!trendsVoOptional.isPresent()) {
                    TradeTrendsVo tradeTrendsVo = new TradeTrendsVo();
                    tradeTrendsVo = new TradeTrendsVo();
                    tradeTrendsVo.setRequestTime(requestTime);
                    tradeTrendsVo.setRequestConsume("0");
                    oneYearList.add(tradeTrendsVo);
                } else {
                    oneYearList.add(trendsVoOptional.get());
                }

            }
        }


        return oneYearList;
    }

    /**
     * @Author wangjinghan
     * @Description 得到指定时间区域内的【每5天】间隔的数据
     * @date: 2021/1/6 16:24
     */
    private List<TradeTrendsVo> getYearTimeData(String date, List<TradeTrendsVo> tradeTrendsLists) {
        List<TradeTrendsVo> tradeVoListData = new LinkedList<>();
        //以12h分割
        Map<Long, Long> requestConsume = new LinkedHashMap<>();
        Map<Long, Long> num = new LinkedHashMap<>();

        for (int i = 1; i <= 12; i++) {
            if (i < 10) {
                requestConsume.put(Long.valueOf(date + "0" + i + "01"), 0L);
                requestConsume.put(Long.valueOf(date + "0" + i + "05"), 0L);
                requestConsume.put(Long.valueOf(date + "0" + i + "10"), 0L);
                requestConsume.put(Long.valueOf(date + "0" + i + "15"), 0L);
                requestConsume.put(Long.valueOf(date + "0" + i + "20"), 0L);
                requestConsume.put(Long.valueOf(date + "0" + i + "25"), 0L);

                num.put(Long.valueOf(date + "0" + i + "01"), 0L);
                num.put(Long.valueOf(date + "0" + i + "05"), 0L);
                num.put(Long.valueOf(date + "0" + i + "10"), 0L);
                num.put(Long.valueOf(date + "0" + i + "15"), 0L);
                num.put(Long.valueOf(date + "0" + i + "20"), 0L);
                num.put(Long.valueOf(date + "0" + i + "25"), 0L);
            } else {
                requestConsume.put(Long.valueOf(date + i + "01"), 0L);
                requestConsume.put(Long.valueOf(date + i + "05"), 0L);
                requestConsume.put(Long.valueOf(date + i + "10"), 0L);
                requestConsume.put(Long.valueOf(date + i + "15"), 0L);
                requestConsume.put(Long.valueOf(date + i + "20"), 0L);
                requestConsume.put(Long.valueOf(date + i + "25"), 0L);

                num.put(Long.valueOf(date + i + "01"), 0L);
                num.put(Long.valueOf(date + i + "05"), 0L);
                num.put(Long.valueOf(date + i + "10"), 0L);
                num.put(Long.valueOf(date + i + "15"), 0L);
                num.put(Long.valueOf(date + i + "20"), 0L);
                num.put(Long.valueOf(date + i + "25"), 0L);
            }
        }


        if (tradeTrendsLists != null && tradeTrendsLists.size() > 0) {
            for (TradeTrendsVo tradeVolumnVo : tradeTrendsLists) {
                //yyyyMMdd
                int day = Integer.valueOf(tradeVolumnVo.getRequestTime().substring(6));
                String d = "";
                Long dayInt = 0L;
                if (day < 5) {
                    d = tradeVolumnVo.getRequestTime().substring(0, 6) + "01";
                    dayInt = Long.valueOf(d); //yyyymmddHHmm
                } else if (day < 10) {
                    d = tradeVolumnVo.getRequestTime().substring(0, 6) + "05";
                    dayInt = Long.valueOf(d); //yyyymmddHHmm
                } else if (day < 15) {
                    d = tradeVolumnVo.getRequestTime().substring(0, 6) + "10";
                    dayInt = Long.valueOf(d); //yyyymmddHHmm
                } else if (day < 20) {
                    d = tradeVolumnVo.getRequestTime().substring(0, 6) + "15";
                    dayInt = Long.valueOf(d); //yyyymmddHHmm
                } else if (day < 25) {
                    d = tradeVolumnVo.getRequestTime().substring(0, 6) + "20";
                    dayInt = Long.valueOf(d); //yyyymmddHHmm
                } else if (day < 31) {
                    d = tradeVolumnVo.getRequestTime().substring(0, 6) + "25";
                    dayInt = Long.valueOf(d); //yyyymmddHHmm
                }


                Long allNum = tradeVolumnVo.getNum();
                if (num.get(dayInt) != null) {
                    allNum = num.get(dayInt) + allNum;
                    num.put(dayInt, allNum);

                    Long requestConsumeNum = Long.valueOf(tradeVolumnVo.getRequestConsume()) * tradeVolumnVo.getNum();
                    if (requestConsume.get(dayInt) != null) {
                        requestConsumeNum = requestConsume.get(dayInt) + requestConsumeNum;
                    }
                    requestConsume.put(dayInt, requestConsumeNum);
                }


            }
        }

        for (Long hour2 : requestConsume.keySet()) {
            TradeTrendsVo tradeTrendsVo = new TradeTrendsVo();
            tradeTrendsVo.setRequestTime(hour2.toString());
            double consume = 0;
            if (0 < num.get(hour2)) {
                consume = requestConsume.get(hour2) / num.get(hour2);
            }
            tradeTrendsVo.setRequestConsume(String.valueOf(consume));
            tradeVoListData.add(tradeTrendsVo);
        }
        return tradeVoListData;
    }


    /**
     * @Author wangjinghan
     * @Description 得到指定时间区域内的【每12h】间隔的数据
     * @date: 2021/1/6 16:24
     */
    private List<TradeTrendsVo> getMonthTimeData(String[] date, List<TradeVolumnVo> tradeTrendsLists) {
        List<TradeTrendsVo> tradeVoListData = new LinkedList<>();
        //以12h分割
        Map<Long, Long> requestConsume = new LinkedHashMap<>();
        Map<Long, Long> num = new LinkedHashMap<>();
        String temp = date[1];//开始时间
        String endDate = date[0].substring(0, 8) + "000000";//开始时间
        requestConsume.put(Long.valueOf(date[1].substring(0, 12)), 0L);
        num.put(Long.valueOf(date[1].substring(0, 12)), 0L);
        while (temp.compareTo(endDate) < 0) {
            //时间加12h
            String addDate = DateUtils.getAddTenMinute(temp, 43200000);
            requestConsume.put(Long.valueOf(addDate.substring(0, 12)), 0L);
            num.put(Long.valueOf(addDate.substring(0, 12)), 0L);
            temp = addDate;
        }

        if (tradeTrendsLists != null && tradeTrendsLists.size() > 0) {
            for (TradeVolumnVo tradeVolumnVo : tradeTrendsLists) {
                int hourItem = Integer.valueOf(tradeVolumnVo.getRequestDate().substring(8, 10));
                String d = "";
                Long hour = 0L;
                if (hourItem >= 12) {
                    d = tradeVolumnVo.getRequestDate().substring(0, 8) + "1200";
                    hour = Long.valueOf(d); //yyyymmddHHmm
                } else {
                    d = tradeVolumnVo.getRequestDate().substring(0, 8) + "0000";
                    hour = Long.valueOf(d); //yyyymmddHHmm
                }

                Long allNum = tradeVolumnVo.getNum();
                if (num.get(hour) != null) {
                    allNum = num.get(hour) + allNum;
                    num.put(hour, allNum);


                    Long requestConsumeNum = tradeVolumnVo.getRequestConsume() * tradeVolumnVo.getNum();
                    if (requestConsume.get(hour) != null) {
                        requestConsumeNum = requestConsume.get(hour) + requestConsumeNum;
                    }
                    requestConsume.put(hour, requestConsumeNum);
                }


            }
        }

        for (Long hour2 : requestConsume.keySet()) {
            TradeTrendsVo tradeTrendsVo = new TradeTrendsVo();
            tradeTrendsVo.setRequestTime(hour2.toString());
            double consume = 0;
            if (0 < num.get(hour2)) {
                consume = requestConsume.get(hour2) / num.get(hour2);
            }
            tradeTrendsVo.setRequestConsume(String.valueOf(consume));
            tradeVoListData.add(tradeTrendsVo);
        }
        return tradeVoListData;
    }

    /**
     * @Author wangjinghan
     * @Description 得到指定时间区域内的【每2h】间隔的数据
     * @date: 2022年3月1日11:34:29
     */
    private List<TradeTrendsVo> getWeekTimeData(String[] date, List<TradeVolumnVo> tradeTrendsLists) {
        List<TradeTrendsVo> tradeVoListData = new LinkedList<>();
        //以2h分割
        Map<Long, Long> requestConsume = new LinkedHashMap<>();
        Map<Long, Long> num = new LinkedHashMap<>();
        String temp = date[1].substring(0, 10) + "0000";//开始时间
        String endDate = date[0].substring(0, 10) + "0000";//开始时间
        requestConsume.put(Long.valueOf(temp.substring(0, 12)), 0L);
        num.put(Long.valueOf(temp.substring(0, 12)), 0L);
        while (temp.compareTo(endDate) < 0) {
            //时间加10s
            String addDate = DateUtils.getAddTenMinute(temp, 7200000);
            requestConsume.put(Long.valueOf(addDate.substring(0, 12)), 0L);
            num.put(Long.valueOf(addDate.substring(0, 12)), 0L);
            temp = addDate;
        }

        if (tradeTrendsLists != null && tradeTrendsLists.size() > 0) {
            for (TradeVolumnVo tradeVolumnVo : tradeTrendsLists) {
                String d = tradeVolumnVo.getRequestDate().substring(0, 10) + "00";
                Long hour = Long.valueOf(d); //yyyymmddHHmm

                Long allNum = tradeVolumnVo.getNum();
                if (num.get(hour) != null) {
                    allNum = num.get(hour) + allNum;
                    num.put(hour, allNum);

                    Long requestConsumeNum = tradeVolumnVo.getRequestConsume() * tradeVolumnVo.getNum();
                    if (requestConsume.get(hour) != null) {
                        requestConsumeNum = requestConsume.get(hour) + requestConsumeNum;
                    }
                    requestConsume.put(hour, requestConsumeNum);
                } else {
                    //d -1小时
                    Long hour2 = Long.valueOf(DateUtils.getAddTenMinute(d + "00", -3600000).substring(0, 12)); //yyyymmddHHmm
                    if (num.get(hour2) != null) {
                        allNum = num.get(hour2) + allNum;
                        num.put(hour2, allNum);


                        Long requestConsumeNum = tradeVolumnVo.getRequestConsume() * tradeVolumnVo.getNum();
                        if (requestConsume.get(hour2) != null) {
                            requestConsumeNum = requestConsume.get(hour2) + requestConsumeNum;
                        }
                        requestConsume.put(hour2, requestConsumeNum);
                    }
                }


            }
        }

        for (Long hour2 : requestConsume.keySet()) {
            TradeTrendsVo tradeTrendsVo = new TradeTrendsVo();
            tradeTrendsVo.setRequestTime(hour2.toString());
            double consume = 0;
            if (0 < num.get(hour2)) {
                consume = requestConsume.get(hour2) / num.get(hour2);
            }
            tradeTrendsVo.setRequestConsume(String.valueOf(consume));
            tradeVoListData.add(tradeTrendsVo);
        }
        return tradeVoListData;
    }

    /**
     * @Author wangjinghan
     * @Description 得到指定时间区域内的【每10min】间隔的数据
     * @date: 2021/1/6 16:24
     */
    private List<TradeTrendsVo> getTenMinuteTimeData(String[] date, List<TradeVolumnVo> tradeTrendsLists) {
        List<TradeTrendsVo> tradeVoListData = new LinkedList<>();
        //以10min分割
        Map<Long, Long> requestConsume = new LinkedHashMap<>();
        Map<Long, Long> num = new LinkedHashMap<>();
        String temp = date[0];//开始时间
        requestConsume.put(Long.valueOf(date[0].substring(0, 12)), 0L);
        num.put(Long.valueOf(date[0].substring(0, 12)), 0L);
        while (temp.compareTo(date[1]) < 0) {
            //时间加10s
            String addDate = DateUtils.getAfterTenMinute(temp);
            requestConsume.put(Long.valueOf(addDate.substring(0, 12)), 0L);
            num.put(Long.valueOf(addDate.substring(0, 12)), 0L);
            temp = addDate;
        }

        if (tradeTrendsLists != null && tradeTrendsLists.size() > 0) {
            for (TradeVolumnVo tradeVolumnVo : tradeTrendsLists) {
                String d = "";
                if (tradeVolumnVo.getRequestDate().length() > 8) {
                    d = tradeVolumnVo.getRequestDate().substring(0, 11) + date[0].substring(11, 12);
                } else {
                    d = tradeVolumnVo.getRequestDate() + date[0].substring(8, 12);
                }
                Long hour = Long.valueOf(d);

                Long allNum = tradeVolumnVo.getNum();
                if (num.get(hour) != null) {
                    allNum = num.get(hour) + allNum;
                }
                num.put(hour, allNum);

                Long requestConsumeNum = tradeVolumnVo.getRequestConsume() * tradeVolumnVo.getNum();
                if (requestConsume.get(hour) != null) {
                    requestConsumeNum = requestConsume.get(hour) + requestConsumeNum;
                }
                requestConsume.put(hour, requestConsumeNum);
            }
        }

        for (Long hour2 : requestConsume.keySet()) {
            TradeTrendsVo tradeTrendsVo = new TradeTrendsVo();
            tradeTrendsVo.setRequestTime(hour2.toString());
            double consume = 0;
            if (0 < num.get(hour2)) {
                consume = requestConsume.get(hour2) / num.get(hour2);
            }
            tradeTrendsVo.setRequestConsume(String.valueOf(consume));
            tradeVoListData.add(tradeTrendsVo);
        }
        return tradeVoListData;
    }


    /**
     * @Author wangjinghan
     * @Description 每天一个点
     * <p>  date  yyyy
     * @date: 2022年2月28日10:30:26
     */
    private List<TradeTrendsVo> getYearsData365(String year, List<TradeTrendsVo> tradeTrendsLists) {
//        平年1年有365天，闰年1年有366天

        int yearDay = Integer.valueOf(year);  //获取当年 天数
        boolean isRun = false;  //是否是闰年
        if (yearDay % 4 == 0 && yearDay % 100 != 0 || yearDay % 400 == 0) {
            isRun = true;
        }
        List<TradeTrendsVo> oneYearList = new ArrayList<>(isRun ? 366 : 355);
        for (int i = 1; i <= 12; i++) {
            for (int y = 1; y <= 31; y++) {
                if (y == 29 && i == 2 && !isRun) {
                    //不是闰年
                    break;
                }
                if (y > 29 && i == 2) {
                    break;
                }

                if (y == 31 && (i == 4 || i == 6 || i == 9 || i == 11)) {
                    //共30天
                    break;
                }
                String requestTime = "";
                if (i >= 10 && y >= 10) {
                    requestTime = year + i + y;
                } else if (i < 10 && y >= 10) {
                    requestTime = year + "0" + i + y;
                } else {
                    requestTime = year + "0" + i + "0" + y;
                }
                String finalRequestTime = requestTime;
                Optional<TradeTrendsVo> trendsVoOptional = tradeTrendsLists.stream().filter(item -> finalRequestTime.equals(item.getRequestTime())).findFirst();
                if (!trendsVoOptional.isPresent()) {
                    TradeTrendsVo tradeTrendsVo = new TradeTrendsVo();
                    tradeTrendsVo = new TradeTrendsVo();
                    tradeTrendsVo.setRequestTime(requestTime);
                    tradeTrendsVo.setFailNum(0L);
                    tradeTrendsVo.setSuccessNum(0L);
                    oneYearList.add(tradeTrendsVo);
                } else {
                    oneYearList.add(trendsVoOptional.get());
                }

            }
        }


        return oneYearList;
    }

    /**
     * @Author wangjinghan
     * @Description 得到指定时间区域内的【每5天】间隔的数据
     * <p>  date  yyyy
     * 1.1     1.5  1.10  1.15    1.20   1.25   2.1  按照这个顺序
     * @date: 2022年2月28日10:30:26
     */
    private List<TradeTrendsVo> getYearsData(String date, List<TradeTrendsVo> tradeTrendsLists) {
        List<TradeTrendsVo> tradeVoListData = new LinkedList<>();
        //以12h分割
        Map<Long, Long> sucNumMap2 = new LinkedHashMap<>();   //成功Map
        Map<Long, Long> failNumMap2 = new LinkedHashMap<>(); //失败Map

        for (int i = 1; i <= 12; i++) {
            if (i < 10) {
                sucNumMap2.put(Long.valueOf(date + "0" + i + "01"), 0L);
                sucNumMap2.put(Long.valueOf(date + "0" + i + "05"), 0L);
                sucNumMap2.put(Long.valueOf(date + "0" + i + "10"), 0L);
                sucNumMap2.put(Long.valueOf(date + "0" + i + "15"), 0L);
                sucNumMap2.put(Long.valueOf(date + "0" + i + "20"), 0L);
                sucNumMap2.put(Long.valueOf(date + "0" + i + "25"), 0L);

                failNumMap2.put(Long.valueOf(date + "0" + i + "01"), 0L);
                failNumMap2.put(Long.valueOf(date + "0" + i + "05"), 0L);
                failNumMap2.put(Long.valueOf(date + "0" + i + "10"), 0L);
                failNumMap2.put(Long.valueOf(date + "0" + i + "15"), 0L);
                failNumMap2.put(Long.valueOf(date + "0" + i + "20"), 0L);
                failNumMap2.put(Long.valueOf(date + "0" + i + "25"), 0L);
            } else {
                sucNumMap2.put(Long.valueOf(date + i + "01"), 0L);
                sucNumMap2.put(Long.valueOf(date + i + "05"), 0L);
                sucNumMap2.put(Long.valueOf(date + i + "10"), 0L);
                sucNumMap2.put(Long.valueOf(date + i + "15"), 0L);
                sucNumMap2.put(Long.valueOf(date + i + "20"), 0L);
                sucNumMap2.put(Long.valueOf(date + i + "25"), 0L);

                failNumMap2.put(Long.valueOf(date + i + "01"), 0L);
                failNumMap2.put(Long.valueOf(date + i + "05"), 0L);
                failNumMap2.put(Long.valueOf(date + i + "10"), 0L);
                failNumMap2.put(Long.valueOf(date + i + "15"), 0L);
                failNumMap2.put(Long.valueOf(date + i + "20"), 0L);
                failNumMap2.put(Long.valueOf(date + i + "25"), 0L);
            }
        }


        if (tradeTrendsLists != null && tradeTrendsLists.size() > 0) {
            for (TradeTrendsVo tradeVolumnVo : tradeTrendsLists) {
                //yyyyMMdd
                int day = Integer.valueOf(tradeVolumnVo.getRequestTime().substring(6));
                String d = "";
                Long dayInt = 0L;
                if (day < 5) {
                    d = tradeVolumnVo.getRequestTime().substring(0, 6) + "01";
                    dayInt = Long.valueOf(d); //yyyymmddHHmm
                } else if (day < 10) {
                    d = tradeVolumnVo.getRequestTime().substring(0, 6) + "05";
                    dayInt = Long.valueOf(d); //yyyymmddHHmm
                } else if (day < 15) {
                    d = tradeVolumnVo.getRequestTime().substring(0, 6) + "10";
                    dayInt = Long.valueOf(d); //yyyymmddHHmm
                } else if (day < 20) {
                    d = tradeVolumnVo.getRequestTime().substring(0, 6) + "15";
                    dayInt = Long.valueOf(d); //yyyymmddHHmm
                } else if (day < 25) {
                    d = tradeVolumnVo.getRequestTime().substring(0, 6) + "20";
                    dayInt = Long.valueOf(d); //yyyymmddHHmm
                } else if (day < 31) {
                    d = tradeVolumnVo.getRequestTime().substring(0, 6) + "25";
                    dayInt = Long.valueOf(d); //yyyymmddHHmm
                }

                Long sucNum = tradeVolumnVo.getSuccessNum();


                if (sucNumMap2.get(dayInt) != null) {
                    sucNum = sucNumMap2.get(dayInt) + sucNum;
                    sucNumMap2.put(dayInt, sucNum);
                }

                Long failNum = tradeVolumnVo.getFailNum();
                if (failNumMap2.get(dayInt) != null) {
                    failNum = failNumMap2.get(dayInt) + failNum;
                    failNumMap2.put(dayInt, failNum);
                }

            }
        }

        for (Long hour2 : sucNumMap2.keySet()) {
            TradeTrendsVo tradeTrendsVo = new TradeTrendsVo();
            tradeTrendsVo.setRequestTime(hour2.toString());

            Long sucNum = sucNumMap2.get(hour2);
            tradeTrendsVo.setSuccessNum(sucNum);

            Long failNum = failNumMap2.get(hour2);
            tradeTrendsVo.setFailNum(failNum);
            tradeVoListData.add(tradeTrendsVo);
        }
        return tradeVoListData;
    }

    /**
     * @Author wangjinghan
     * @Description 得到指定时间区域内的【每12小时】间隔的数据
     * @date: 2022年2月28日10:30:26
     */
    private List<TradeTrendsVo> getMonthsData(String[] date, List<TradeVolumnVo> tradeTrendsLists) {
        List<TradeTrendsVo> tradeVoListData = new LinkedList<>();
        //以12h分割
        Map<Long, Long> sucNumMap2 = new LinkedHashMap<>();   //成功Map
        Map<Long, Long> failNumMap2 = new LinkedHashMap<>(); //失败Map
        Map<Long, Long> respNumMap2 = new LinkedHashMap<>();
        String temp = date[1];//开始时间
        String endDate = date[0];//开始时间
        sucNumMap2.put(Long.valueOf(date[1].substring(0, 12)), 0L);    //开始时间成功数
        failNumMap2.put(Long.valueOf(date[1].substring(0, 12)), 0L);   //开始时间失败数
        respNumMap2.put(Long.valueOf(date[1].substring(0, 12)), 0L);   //开始时间失败数
        while (Long.valueOf(temp) < Long.valueOf(endDate)) {       //把区间内 每间隔2小时的点存到map里，后续进行更新
            //时间加12小时
            String addDate = DateUtils.getAddTenMinute(temp, 43200000);
            sucNumMap2.put(Long.valueOf(addDate.substring(0, 12)), 0L);
            failNumMap2.put(Long.valueOf(addDate.substring(0, 12)), 0L);
            respNumMap2.put(Long.valueOf(addDate.substring(0, 12)), 0L);
            temp = addDate;
        }

        if (tradeTrendsLists != null && tradeTrendsLists.size() > 0) {
            for (TradeVolumnVo tradeVolumnVo : tradeTrendsLists) {

                int hourItem = Integer.valueOf(tradeVolumnVo.getRequestDate().substring(8, 10));
                String d = "";
                Long hour = 0L;
                if (hourItem >= 12) {
                    d = tradeVolumnVo.getRequestDate().substring(0, 8) + "1200";
                    hour = Long.valueOf(d); //yyyymmddHHmm
                } else {
                    d = tradeVolumnVo.getRequestDate().substring(0, 8) + "0000";
                    hour = Long.valueOf(d); //yyyymmddHHmm
                }

                Long sucNum = tradeVolumnVo.getSuccessNum();


                if (sucNumMap2.get(hour) != null) {
                    sucNum = sucNumMap2.get(hour) + sucNum;
                    sucNumMap2.put(hour, sucNum);
                }

                Long failNum = tradeVolumnVo.getFail();
                if (failNumMap2.get(hour) != null) {
                    failNum = failNumMap2.get(hour) + failNum;
                    failNumMap2.put(hour, failNum);
                }

                Long respNum = tradeVolumnVo.getResponseNum();
                if (respNumMap2.get(hour) != null) {
                    respNum = respNumMap2.get(hour) + respNum;
                    respNumMap2.put(hour, respNum);
                }

            }
        }

        for (Long hour2 : sucNumMap2.keySet()) {
            TradeTrendsVo tradeTrendsVo = new TradeTrendsVo();
            tradeTrendsVo.setRequestTime(hour2.toString());

            Long sucNum = sucNumMap2.get(hour2);
            tradeTrendsVo.setSuccessNum(sucNum);

            Long failNum = failNumMap2.get(hour2);
            tradeTrendsVo.setFailNum(failNum);

            Long respNum = respNumMap2.get(hour2);
            tradeTrendsVo.setResponseNum(respNum);
            tradeVoListData.add(tradeTrendsVo);
        }
        return tradeVoListData;
    }

    /**
     * @Author wangjinghan
     * @Description 得到指定时间区域内的【每2小时】间隔的数据
     * @date: 2022年2月28日10:30:26
     */
    private List<TradeTrendsVo> getTwoHoursData(String[] date, List<TradeVolumnVo> tradeTrendsLists) {
        List<TradeTrendsVo> tradeVoListData = new LinkedList<>();
        //以2h分割
        Map<Long, Long> sucNumMap2 = new LinkedHashMap<>();   //成功Map
        Map<Long, Long> failNumMap2 = new LinkedHashMap<>(); //失败Map
        Map<Long, Long> respNumMap2 = new LinkedHashMap<>();
        String temp = date[1].substring(0, 10) + "0000";//开始时间
//        String endDate = date[0].substring(0, 8) + "000000";//开始时间
        String endDate = date[0].substring(0, 10) + "0000";//开始时间
        sucNumMap2.put(Long.valueOf(date[1].substring(0, 12)), 0L);    //开始时间成功数
        failNumMap2.put(Long.valueOf(date[1].substring(0, 12)), 0L);   //开始时间失败数
        respNumMap2.put(Long.valueOf(date[1].substring(0, 12)), 0L);   //开始时间失败数
        while (Long.valueOf(temp) < Long.valueOf(endDate)) {       //把区间内 每间隔2小时的点存到map里，后续进行更新
            //时间加2小时
            String addDate = DateUtils.getAddTenMinute(temp, 7200000);
            sucNumMap2.put(Long.valueOf(addDate.substring(0, 12)), 0L);
            failNumMap2.put(Long.valueOf(addDate.substring(0, 12)), 0L);
            respNumMap2.put(Long.valueOf(addDate.substring(0, 12)), 0L);
            temp = addDate;
        }

        if (tradeTrendsLists != null && tradeTrendsLists.size() > 0) {
            for (TradeVolumnVo tradeVolumnVo : tradeTrendsLists) {
                String d = tradeVolumnVo.getRequestDate().substring(0, 10) + "00";
                Long hour = Long.valueOf(d); //yyyymmddHHmm

                Long sucNum = tradeVolumnVo.getSuccessNum();


                if (sucNumMap2.get(hour) != null) {
                    sucNum = sucNumMap2.get(hour) + sucNum;
                    sucNumMap2.put(hour, sucNum);
                } else {
                    //d -1小时
                    Long hour2 = Long.valueOf(DateUtils.getAddTenMinute(d + "00", -3600000).substring(0, 12)); //yyyymmddHHmm
                    sucNum = tradeVolumnVo.getSuccessNum();
                    if (sucNumMap2.get(hour2) != null) {
                        sucNum = sucNumMap2.get(hour2) + sucNum;
                        sucNumMap2.put(hour2, sucNum);
                    }
                }


                Long failNum = tradeVolumnVo.getFail();
                if (failNumMap2.get(hour) != null) {
                    failNum = failNumMap2.get(hour) + failNum;
                    failNumMap2.put(hour, failNum);
                } else {
                    //d -1小时
                    Long hour2 = Long.valueOf(DateUtils.getAddTenMinute(d + "00", -3600000).substring(0, 12)); //yyyymmddHHmm
                    failNum = tradeVolumnVo.getFail();
                    if (failNumMap2.get(hour2) != null) {
                        failNum = failNumMap2.get(hour2) + failNum;
                        failNumMap2.put(hour2, failNum);
                    }
                }

                Long respNum = tradeVolumnVo.getResponseNum();
                if (respNumMap2.get(hour) != null) {
                    respNum = respNumMap2.get(hour) + respNum;
                    respNumMap2.put(hour, respNum);
                } else {
                    //d -1小时
                    Long hour2 = Long.valueOf(DateUtils.getAddTenMinute(d + "00", -3600000).substring(0, 12)); //yyyymmddHHmm
                    respNum = tradeVolumnVo.getResponseNum();
                    if (respNumMap2.get(hour2) != null) {
                        respNum = respNumMap2.get(hour2) + respNum;
                        respNumMap2.put(hour2, respNum);
                    }
                }

            }
        }

        for (Long hour2 : sucNumMap2.keySet()) {
            TradeTrendsVo tradeTrendsVo = new TradeTrendsVo();
            tradeTrendsVo.setRequestTime(hour2.toString());

            Long sucNum = sucNumMap2.get(hour2);
            tradeTrendsVo.setSuccessNum(sucNum);

            Long failNum = failNumMap2.get(hour2);
            tradeTrendsVo.setFailNum(failNum);

            Long respNum = respNumMap2.get(hour2);
            tradeTrendsVo.setResponseNum(respNum);

            tradeVoListData.add(tradeTrendsVo);


        }
        return tradeVoListData;
    }

    /**
     * @Author wangjinghan
     * @Description 得到指定时间区域内的【每10min】间隔的数据
     * @date: 2021/1/6 16:24
     */
    private List<TradeTrendsVo> getTenMinuteData(String[] date, List<TradeVolumnVo> tradeTrendsLists) {
        List<TradeTrendsVo> tradeVoListData = new LinkedList<>();
        //以10min分割
        Map<Long, Long> sucNumMap2 = new LinkedHashMap<>();
        Map<Long, Long> failNumMap2 = new LinkedHashMap<>();
        Map<Long, Long> respNumMap2 = new LinkedHashMap<>();
        String temp = date[0];//开始时间
        sucNumMap2.put(Long.valueOf(date[0].substring(0, 12)), 0L);
        failNumMap2.put(Long.valueOf(date[0].substring(0, 12)), 0L);
        respNumMap2.put(Long.valueOf(date[0].substring(0, 12)), 0L);
        while (temp.compareTo(date[1]) < 0) {
            //时间加10s
            String addDate = DateUtils.getAfterTenMinute(temp);
            sucNumMap2.put(Long.valueOf(addDate.substring(0, 12)), 0L);
            failNumMap2.put(Long.valueOf(addDate.substring(0, 12)), 0L);
            respNumMap2.put(Long.valueOf(addDate.substring(0, 12)), 0L);
            temp = addDate;
        }

        if (tradeTrendsLists != null && tradeTrendsLists.size() > 0) {
            for (TradeVolumnVo tradeVolumnVo : tradeTrendsLists) {
                String d = "";
                if (tradeVolumnVo.getRequestDate().length() > 8) {
                    d = tradeVolumnVo.getRequestDate().substring(0, 11) + date[0].substring(11, 12);
                } else {
                    d = tradeVolumnVo.getRequestDate() + date[0].substring(8, 12);
                }
                Long hour = Long.valueOf(d);

                Long sucNum = tradeVolumnVo.getSuccessNum();
                if (sucNumMap2.get(hour) != null) {
                    sucNum = sucNumMap2.get(hour) + sucNum;
                }
                sucNumMap2.put(hour, sucNum);

                Long failNum = tradeVolumnVo.getFail();
                if (failNumMap2.get(hour) != null) {
                    failNum = failNumMap2.get(hour) + failNum;
                }
                failNumMap2.put(hour, failNum);

                Long respNum = tradeVolumnVo.getResponseNum();
                if (respNumMap2.get(hour) != null) {
                    respNum = respNumMap2.get(hour) + respNum;
                }
                respNumMap2.put(hour, respNum);


            }
        }

        for (Long hour2 : sucNumMap2.keySet()) {
            TradeTrendsVo tradeTrendsVo = new TradeTrendsVo();
            tradeTrendsVo.setRequestTime(hour2.toString());

            Long sucNum = sucNumMap2.get(hour2);
            tradeTrendsVo.setSuccessNum(sucNum);

            Long failNum = failNumMap2.get(hour2);
            tradeTrendsVo.setFailNum(failNum);

            Long respNum = respNumMap2.get(hour2);
            tradeTrendsVo.setResponseNum(respNum);

            tradeVoListData.add(tradeTrendsVo);
        }
        return tradeVoListData;
    }

    /**
     * @Author wangjinghan
     * @Description 得到指定时间区域内的【每10s】间隔的数据
     * @date: 2021/1/6 16:24
     */
    private List<TradeTrendsVo> getHourData(String[] date, List<TradeVolumnVo> tradeTrendsLists) {
        List<TradeTrendsVo> tradeVoListData = new LinkedList<>();
        ;
        //以10s分割
        Map<Long, Long> sucNumMap2 = new LinkedHashMap<>();
        Map<Long, Long> failNumMap2 = new LinkedHashMap<>();
        Map<Long, Long> tpsNumMap2 = new LinkedHashMap<>();
        Map<Long, Long> respNumMap2 = new LinkedHashMap<>();
        String temp = date[0];//开始时间
        sucNumMap2.put(Long.valueOf(date[0]), 0L);
        failNumMap2.put(Long.valueOf(date[0]), 0L);
        while (temp.compareTo(date[1]) < 0) {
            //时间加10s
            String addDate = DateUtils.getAddOneHour(temp);
            sucNumMap2.put(Long.valueOf(addDate), 0L);
            failNumMap2.put(Long.valueOf(addDate), 0L);
            tpsNumMap2.put(Long.valueOf(addDate), 0L);
            respNumMap2.put(Long.valueOf(addDate), 0L);
            temp = addDate;
        }

        if (tradeTrendsLists != null && tradeTrendsLists.size() > 0) {
            for (TradeVolumnVo tradeVolumnVo : tradeTrendsLists) {
                String d = tradeVolumnVo.getRequestDate();
                Long hour = Long.valueOf(d.substring(0, d.length() - 2) + date[0].substring(12, 14));

                Long sucNum = tradeVolumnVo.getSuccessNum();
                if (sucNumMap2.get(hour) != null) {
                    sucNum = sucNumMap2.get(hour) + sucNum;
                }
                sucNumMap2.put(hour, sucNum);
                Long failNum = tradeVolumnVo.getFail();
                if (failNumMap2.get(hour) != null) {
                    failNum = failNumMap2.get(hour) + failNum;
                }
                failNumMap2.put(hour, failNum);

                Long respNum = tradeVolumnVo.getResponseNum();
                if (respNumMap2.get(hour) != null) {
                    respNum = respNumMap2.get(hour) + respNum;
                }
                respNumMap2.put(hour, respNum);

            }
        }

        for (Long hour2 : sucNumMap2.keySet()) {
            TradeTrendsVo tradeTrendsVo = new TradeTrendsVo();
            tradeTrendsVo.setRequestTime(hour2.toString());

            Long sucNum = sucNumMap2.get(hour2);
            tradeTrendsVo.setSuccessNum(sucNum);

            Long failNum = failNumMap2.get(hour2);
            tradeTrendsVo.setFailNum(failNum);

            Long respNum = respNumMap2.get(hour2);
            tradeTrendsVo.setResponseNum(respNum);

//                    tradeTrendsVo.setTicks(ticks);

            tradeVoListData.add(tradeTrendsVo);
        }
        return tradeVoListData;
    }

    private List<Long> getBaseProductList(Long baseProductId) {
        ApiVO apiVO = new ApiVO();
        apiVO.setBackserviceId(baseProductId);
        List<ApiVO> apiVOList = apiService.selectApiList(apiVO);
        List<Long> apiIds = new ArrayList();
        if (apiVOList.size() > 0) {
            for (ApiVO apis : apiVOList) {
                apiIds.add(apis.getId());
            }
        }
        //去重
        return new ArrayList<>(new TreeSet<>(apiIds));
    }

    private List<String> getApiCodeBybaseProductId(Long baseProductId) {
        ApiVO apiVO = new ApiVO();
        apiVO.setBackserviceId(baseProductId);
        List<ApiVO> apiVOList = apiService.selectApiList(apiVO);
        List<String> apiIds = new ArrayList();
        if (apiVOList.size() > 0) {
            for (ApiVO apis : apiVOList) {
                apiIds.add(apis.getApiCode());
            }
        }
        //去重
        return new ArrayList<>(new TreeSet<>(apiIds));
    }

    //  获取周/月交易趋势
    private List<TradeTrendsVo> tradingTrendsWM(String flag, GatewayLogDayVO gatewayLogDayVO, String nowDate) {
        List<TradeTrendsVo> tradeVoListData = new LinkedList<>();
        List<String> list = new LinkedList<>();
        int len = 0;
        if (flag.equals("week")) {
            try {
                list = DateUtils.getLastDays(nowDate.substring(0, 8), 7);
            } catch (Exception e) {
                logger.error("获取近七日日期列表失败");
            } finally {

            }
            Collections.sort(list);
            len = list.size();
        } else {
            try {
                list = DateUtils.getLastDays(nowDate.substring(0, 8), 30);
            } catch (Exception e) {
                logger.error("获取近30日日期列表失败");
            } finally {

            }
            Collections.sort(list);
            len = list.size();
        }
        gatewayLogDayVO.setBeginDate(list.get(0));
        gatewayLogDayVO.setEndDate(list.get(list.size() - 1));
        List<TradeTrendsVo> tradeVoLists = new LinkedList<>();
        tradeVoLists = gatewayLogDayService.countNumBydate(gatewayLogDayVO);
        Map<String, Integer> mapWeek = new LinkedHashMap<String, Integer>(); // 返回
        for (int i = 0; i < len; i++) {
            mapWeek.put(list.get(i), 0);
        }
        for (String key : mapWeek.keySet()) {
            TradeTrendsVo tradeTrends = new TradeTrendsVo();
            tradeTrends.setRequestTime(key);
            tradeTrends.setNum(0L);
            tradeTrends.setSuccessNum(0L);
            tradeTrends.setFailNum(0L);
            if (tradeVoLists != null && tradeVoLists.size() > 0) {
                for (TradeTrendsVo tradeTrendsVo : tradeVoLists) {
                    if (key.equals(tradeTrendsVo.getRequestTime())) {
                        tradeTrends.setNum(tradeTrendsVo.getNum());
                        tradeTrends.setSuccessNum(tradeTrendsVo.getSuccessNum());
                        tradeTrends.setFailNum(tradeTrendsVo.getFailNum());
                        tradeTrends.setRequestConsume(tradeTrendsVo.getRequestConsume());
                        break;
                    }
                }
            }
            tradeVoListData.add(tradeTrends);
        }
        return tradeVoListData;
    }

    /**
     * @param appCode
     * @param type
     * @param env
     * @return org.springblade.core.tool.api.R<java.util.List < com.dhcc.bpm.modules.log.vo.TradeAppVo>>
     * @Description 交易趋势, 按渠道号查询
     * @Author xiafayu
     * @Date 2020/2/24 15:20
     **/
    @GetMapping("/tradingAppTrends/{appCode}")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "交易趋势")
    @Log(title = "交易趋势,按渠道号查询", businessType = BusinessType.SELECT)
    public R<List<TradeAppVo>> tradingAppTrends(@PathVariable("appCode") String appCode, @ApiParam(value = "type", required = true) @RequestParam String type, @ApiParam(value = "env", required = true) @RequestParam String env) throws Exception {
        String nowDate = DateUtils.dateTime();
        List<TradeAppVo> appList = new ArrayList<TradeAppVo>();
        List<TradeAppVo> dataList = new ArrayList<>();
        GatewayLogDayVO gatewayLogDayVO = new GatewayLogDayVO();
        gatewayLogDayVO.setEnv(env);
        String flag = "";
        switch (type) {
            case "day":
                GatewayLogMinuteVO gatewayLogMinuteVO = new GatewayLogMinuteVO();
                gatewayLogMinuteVO.setRequestDate(nowDate.substring(0, 8));
                gatewayLogMinuteVO.setOpcAppCode(appCode);
                gatewayLogMinuteVO.setEnv(env);
                appList = gatewayLogMinuteService.selectApiCountByDay(gatewayLogMinuteVO);
                Map<Integer, Integer> mapDay = new LinkedHashMap<Integer, Integer>();
                for (int i = 0; i < 12; i++) {
                    mapDay.put(i * 2, 0);
                }

                if (appList != null && appList.size() > 0) {
                    for (TradeAppVo tradeAppVo : appList) {
                        int requestNum = tradeAppVo.getRequestNum();
                        int hour = (int) Math.floor(Integer.valueOf(tradeAppVo.getRequestDate()) / 2);
                        mapDay.put(hour * 2, mapDay.get(hour * 2) + requestNum);
                    }
                }

                for (Integer hour : mapDay.keySet()) {
                    TradeAppVo appVo = new TradeAppVo();
                    Integer num = mapDay.get(hour);
                    appVo.setRequestDate(String.valueOf(hour) + ":00");
                    appVo.setRequestNum(num);
                    dataList.add(appVo);
                }
                break;
            case "week": //下一个case也执行
                flag = "week";
            case "month":
                List<String> list = new LinkedList<>();
                int len = 0;
                if (flag.equals("week")) {
                    list = DateUtils.getWeekEveryDays(nowDate);
                    len = list.size();
                } else {
                    list = DateUtils.getMonthEveryDays(nowDate);
                    len = list.size();
                }
                gatewayLogDayVO.setBeginDate(list.get(0));
                gatewayLogDayVO.setEndDate(list.get(list.size() - 1));
                gatewayLogDayVO.setOpcAppCode(appCode);
                appList = gatewayLogDayService.selectCountByDate(gatewayLogDayVO);
                Map<String, Integer> mapWeek = new LinkedHashMap<String, Integer>(); // 返回
                for (int i = 0; i < len; i++) {
                    mapWeek.put(list.get(i), 0);
                }
                for (String key : mapWeek.keySet()) {
                    TradeAppVo appVo = new TradeAppVo();
                    appVo.setRequestDate(key);
                    appVo.setRequestNum(0);
                    if (appList != null && appList.size() > 0) {
                        for (TradeAppVo data : appList) {
                            if (key.equals(data.getRequestDate())) {
                                appVo.setRequestNum(data.getRequestNum());
                                break;
                            }
                        }
                    }
                    dataList.add(appVo);
                }
                break;
            case "year":
                String beginDate = nowDate.substring(0, 4) + "0101";
                String endDate = nowDate.substring(0, 4) + "1231";
                gatewayLogDayVO.setBeginDate(beginDate);
                gatewayLogDayVO.setEndDate(endDate);
                gatewayLogDayVO.setOpcAppCode(appCode);
                appList = gatewayLogDayService.selectCountByYear(gatewayLogDayVO);
                Map<String, Integer> mapYear = new LinkedHashMap<String, Integer>(); // 返回
                for (int i = 1; i <= 12; i++) {
                    mapYear.put(String.valueOf(i), 0);
                }
                for (String key : mapYear.keySet()) {
                    TradeAppVo appVo = new TradeAppVo();
                    appVo.setRequestDate(key);
                    appVo.setRequestNum(0);
                    if (appList != null && appList.size() > 0) {
                        for (TradeAppVo app : appList) {
                            app.setRequestDate(String.valueOf(Integer.parseInt(app.getRequestDate())));
                            if (key.equals(app.getRequestDate())) {
                                appVo.setRequestNum(app.getRequestNum());
                                break;
                            }
                        }
                    }
                    dataList.add(appVo);
                }
                break;
            default:
                break;
        }
        // 整理给前台返回格式
        List<TradeAppVo> logList = new ArrayList<>();
        if (dataList != null && dataList.size() > 0) {
            for (TradeAppVo data : dataList) {
                TradeAppVo gate = new TradeAppVo();
                gate.setRequestDate(data.getRequestDate());
                gate.setRequestNum(data.getRequestNum());
                logList.add(gate);
            }
        }
        return R.data(logList);
    }

    /**
     * @param orgaCard
     * @param type
     * @return org.springblade.core.tool.api.R<java.util.List < com.dhcc.bpm.modules.log.vo.TradeAppVo>>
     * @Description 交易趋势, 按渠道号查询
     * @Author xiafayu
     * @Date 2020/2/24 15:20
     **/
    @GetMapping("/tradingOrgaTrends/{orgaCard}")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "交易趋势")
    @Log(title = "交易趋势,按渠道号查询", businessType = BusinessType.SELECT)
    public R<List<TradeAppVo>> tradingOrgaTrends(@ApiParam("orgaCard") String orgaCard, @ApiParam(value = "type", required = true) @RequestParam String type, @ApiParam(value = "env", required = true) @RequestParam String env) throws Exception {
        String nowDate = DateUtils.dateTime();
        List<TradeAppVo> appList = new ArrayList<>();
        List<TradeAppVo> dataList = new ArrayList<>();
        GatewayLogDayVO gatewayLogDayVO = new GatewayLogDayVO();
        gatewayLogDayVO.setEnv(env);
        String flag = "";
        switch (type) {
            case "day":
                GatewayLogMinuteVO gatewayLogMinuteVO = new GatewayLogMinuteVO();
                gatewayLogMinuteVO.setRequestDate(nowDate);
                gatewayLogMinuteVO.setOpcOrgaCode(orgaCard);
                gatewayLogMinuteVO.setEnv(env);
                appList = gatewayLogMinuteService.selectCountByDay(gatewayLogMinuteVO);
                Map<Integer, Integer> mapDay = new LinkedHashMap<Integer, Integer>();
                for (int i = 0; i < 12; i++) {
                    mapDay.put(i * 2, 0);
                }

                if (appList != null && appList.size() > 0) {
                    for (TradeAppVo tradeAppVo : appList) {
                        int requestNum = tradeAppVo.getRequestNum();
                        int hour = (int) Math.floor(Integer.valueOf(tradeAppVo.getRequestDate()) / 2);
                        mapDay.put(hour * 2, mapDay.get(hour * 2) + requestNum);
                    }
                }

                for (Integer hour : mapDay.keySet()) {
                    TradeAppVo appVo = new TradeAppVo();
                    Integer num = mapDay.get(hour);
                    appVo.setRequestDate(String.valueOf(hour) + ":00");
                    appVo.setRequestNum(num);
                    dataList.add(appVo);
                }
                break;
            case "week": //下一个case也执行
                flag = "week";
            case "month":
                List<String> list = new LinkedList<>();
                int len = 0;
                if (flag.equals("week")) {
                    list = DateUtils.getWeekEveryDays(nowDate);
                    len = list.size();
                } else {
                    list = DateUtils.getMonthEveryDays(nowDate);
                    len = list.size();
                }
                gatewayLogDayVO.setBeginDate(list.get(0));
                gatewayLogDayVO.setEndDate(list.get(list.size() - 1));
                gatewayLogDayVO.setOpcOrgaCode(orgaCard);
                appList = gatewayLogDayService.selectCountByDate(gatewayLogDayVO);
                Map<String, Integer> mapWeek = new LinkedHashMap<String, Integer>(); // 返回
                for (int i = 0; i < len; i++) {
                    mapWeek.put(list.get(i), 0);
                }
                for (String key : mapWeek.keySet()) {
                    TradeAppVo appVo = new TradeAppVo();
                    appVo.setRequestDate(key);
                    appVo.setRequestNum(0);
                    if (appList != null && appList.size() > 0) {
                        for (TradeAppVo data : appList) {
                            if (key.equals(data.getRequestDate())) {
                                appVo.setRequestNum(data.getRequestNum());
                                break;
                            }
                        }
                    }
                    dataList.add(appVo);
                }
                break;
            case "year":
                String beginDate = nowDate.substring(0, 4) + "0101";
                String endDate = nowDate.substring(0, 4) + "1231";
                gatewayLogDayVO.setBeginDate(beginDate);
                gatewayLogDayVO.setEndDate(endDate);
                gatewayLogDayVO.setOpcOrgaCode(orgaCard);
                appList = gatewayLogDayService.selectCountByYear(gatewayLogDayVO);
                Map<String, Integer> mapYear = new LinkedHashMap<String, Integer>(); // 返回
                for (int i = 1; i <= 12; i++) {
                    mapYear.put(String.valueOf(i), 0);
                }
                for (String key : mapYear.keySet()) {
                    TradeAppVo appVo = new TradeAppVo();
                    appVo.setRequestDate(key);
                    appVo.setRequestNum(0);
                    if (appList != null && appList.size() > 0) {
                        for (TradeAppVo app : appList) {
                            app.setRequestDate(String.valueOf(Integer.parseInt(app.getRequestDate())));
                            if (key.equals(app.getRequestDate())) {
                                appVo.setRequestNum(app.getRequestNum());
                                break;
                            }
                        }
                    }
                    dataList.add(appVo);
                }
                break;
            default:
                break;
        }
        return R.data(dataList);
    }

    /**
     * @param productId
     * @param type
     * @return org.springblade.core.tool.api.R<java.util.List < com.dhcc.bpm.modules.log.vo.TradeAppVo>>
     * @Description 交易趋势, 按产品号查询
     * @Author xiafayu
     * @Date 2020/2/24 15:20
     **/
    @GetMapping("/tradingProTrends/{productId}")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "交易趋势")
    @Log(title = "交易趋势,按渠道号查询", businessType = BusinessType.SELECT)
    public R<List<TradeAppVo>> tradingProTrends(@PathVariable("productId") String productId, @ApiParam(value = "type", required = true) @RequestParam String type, @ApiParam(value = "env", required = true) @RequestParam String env) throws Exception {
        String nowDate = DateUtils.dateTime();
        List<TradeAppVo> appList = new ArrayList<>();
        List<TradeAppVo> dataList = new ArrayList<>();
        GatewayLogDayVO gatewayLogDayVO = new GatewayLogDayVO();
        gatewayLogDayVO.setEnv(env);
        String flag = "";

        // 求某一产品下API列表 共用
        IPage<ApiVO> req = new Page<ApiVO>();
        req.setCurrent(1);
        req.setSize(99999999); // 不分页，查所有
        ApiVO apiVO = new ApiVO();
        apiVO.setOpcProductId(Long.valueOf(productId));
        IPage<ApiVO> page = apiService.selectProductApiList(req, apiVO);

        switch (type) {
            case "day":
                if (page.getRecords() != null && page.getRecords().size() > 0) {
                    for (ApiVO vo : page.getRecords()) {
                        GatewayLogMinuteVO gatewayLogMinuteVO = new GatewayLogMinuteVO();
                        gatewayLogMinuteVO.setRequestDate(nowDate);
                        gatewayLogMinuteVO.setOpcApiCode(vo.getApiCode());
                        gatewayLogMinuteVO.setEnv(env);
                        List<TradeAppVo> oneApiList = gatewayLogMinuteService.selectCountByDay(gatewayLogMinuteVO);
                        if (oneApiList != null && oneApiList.size() > 0) {
                            for (TradeAppVo tVo : oneApiList) {
                                appList.add(tVo);
                            }
                        }
                    }
                }

                Map<Integer, Integer> mapDay = new LinkedHashMap<Integer, Integer>();
                for (int i = 0; i < 12; i++) {
                    mapDay.put(i * 2, 0);
                }
                for (TradeAppVo tradeAppVo : appList) {
                    int requestNum = tradeAppVo.getRequestNum();
                    int hour = (int) Math.floor(Integer.valueOf(tradeAppVo.getRequestDate()) / 2);
                    mapDay.put(hour * 2, mapDay.get(hour * 2) + requestNum);
                }
                for (Integer hour : mapDay.keySet()) {
                    TradeAppVo appVo = new TradeAppVo();
                    Integer num = mapDay.get(hour);
                    appVo.setRequestDate(String.valueOf(hour) + ":00");
                    appVo.setRequestNum(num);
                    dataList.add(appVo);
                }
                break;
            case "week": //下一个case也执行
                flag = "week";
            case "month":
                List<String> list = new LinkedList<>();
                int len = 0;
                if (flag.equals("week")) {
                    list = DateUtils.getWeekEveryDays(nowDate);
                    len = list.size();
                } else {
                    list = DateUtils.getMonthEveryDays(nowDate);
                    len = list.size();
                }
                gatewayLogDayVO.setBeginDate(list.get(0));
                gatewayLogDayVO.setEndDate(list.get(list.size() - 1));

                if (page.getRecords() != null && page.getRecords().size() > 0) {
                    for (ApiVO vo : page.getRecords()) {
                        gatewayLogDayVO.setOpcApiCode(vo.getApiCode());
                        List<TradeAppVo> oneApiList = gatewayLogDayService.selectCountByDate(gatewayLogDayVO);
                        if (oneApiList != null && oneApiList.size() > 0) {
                            for (TradeAppVo tVo : oneApiList) {
                                appList.add(tVo);
                            }
                        }
                    }
                }

                Map<String, Integer> mapWeek = new LinkedHashMap<String, Integer>(); // 返回
                for (int i = 0; i < len; i++) {
                    mapWeek.put(list.get(i), 0);
                }
                for (String key : mapWeek.keySet()) {
                    TradeAppVo appVo = new TradeAppVo();
                    appVo.setRequestDate(key);
                    appVo.setRequestNum(0);
                    for (TradeAppVo data : appList) {
                        if (key.equals(data.getRequestDate())) {
                            appVo.setRequestNum(appVo.getRequestNum() + data.getRequestNum());
                        }
                    }
                    dataList.add(appVo);
                }
                break;
            case "year":
                String beginDate = nowDate.substring(0, 4) + "0101";
                String endDate = nowDate.substring(0, 4) + "1231";
                gatewayLogDayVO.setBeginDate(beginDate);
                gatewayLogDayVO.setEndDate(endDate);

                if (page.getRecords() != null && page.getRecords().size() > 0) {
                    for (ApiVO vo : page.getRecords()) {
                        gatewayLogDayVO.setOpcApiCode(vo.getApiCode());
                        List<TradeAppVo> oneApiList = gatewayLogDayService.selectCountByYear(gatewayLogDayVO);
                        if (oneApiList != null && oneApiList.size() > 0) {
                            for (TradeAppVo tVo : oneApiList) {
                                appList.add(tVo);
                            }
                        }
                    }
                }

                Map<String, Integer> mapYear = new LinkedHashMap<String, Integer>(); // 返回
                for (int i = 1; i <= 12; i++) {
                    mapYear.put(String.valueOf(i), 0);
                }
                for (String key : mapYear.keySet()) {
                    TradeAppVo appVo = new TradeAppVo();
                    appVo.setRequestDate(key);
                    appVo.setRequestNum(0);
                    for (TradeAppVo app : appList) {
                        app.setRequestDate(String.valueOf(Integer.parseInt(app.getRequestDate())));
                        if (key.equals(app.getRequestDate())) {
                            appVo.setRequestNum(appVo.getRequestNum() + app.getRequestNum());
                        }
                    }
                    dataList.add(appVo);
                }
                break;
            default:
                break;
        }
        return R.data(dataList);
    }

    /**
     * @param sysId
     * @param type
     * @return org.springblade.core.tool.api.R<java.util.List < com.dhcc.bpm.modules.log.vo.TradeAppVo>>
     * @Description 交易趋势, 按系统号查询
     * @Author xiafayu
     * @Date 2020/2/24 15:20
     **/
    @GetMapping("/tradingSysTrends/{sysId}")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "交易趋势")
    @Log(title = "交易趋势,按系统号查询", businessType = BusinessType.SELECT)
    public R<List<TradeAppVo>> tradingSysTrends(@PathVariable("sysId") String sysId, @ApiParam(value = "type", required = true) @RequestParam String type, @ApiParam(value = "env", required = true) @RequestParam String env) throws Exception {
        String nowDate = DateUtils.dateTime();
        List<TradeAppVo> appList = new ArrayList<>();
        List<TradeAppVo> dataList = new ArrayList<>();
        GatewayLogDayVO gatewayLogDayVO = new GatewayLogDayVO();
        gatewayLogDayVO.setEnv(env);

        // 某一系统下产品集合
        List<Product> sysProlist = productService.syslist(sysId);
        String flag = "";
        switch (type) {
            case "day":
                IPage<ApiVO> req = new Page<ApiVO>();
                req.setCurrent(1);
                req.setSize(99999999); // 不分页，查所有

                if (sysProlist != null && sysProlist.size() > 0) {
                    // 产品下API统计
                    for (Product proVO : sysProlist) {
                        ApiVO apiVO = new ApiVO();
                        apiVO.setOpcProductId(proVO.getId());
                        IPage<ApiVO> page = apiService.selectProductApiList(req, apiVO);
                        if (page.getRecords() != null && page.getRecords().size() > 0) {
                            for (ApiVO vo : page.getRecords()) {
                                GatewayLogMinuteVO gatewayLogMinuteVO = new GatewayLogMinuteVO();
                                gatewayLogMinuteVO.setRequestDate(nowDate);
                                if (vo != null && vo.getApiCode() != null) {
                                    gatewayLogMinuteVO.setOpcApiCode(vo.getApiCode());
                                }
                                gatewayLogMinuteVO.setEnv(env);

                                List<TradeAppVo> oneApiList = gatewayLogMinuteService.selectCountByDay(gatewayLogMinuteVO);
                                if (oneApiList != null && oneApiList.size() > 0) {
                                    for (TradeAppVo tVo : oneApiList) {
                                        appList.add(tVo);
                                    }
                                }
                            }
                        }
                    }
                }

                Map<Integer, Integer> mapDay = new LinkedHashMap<Integer, Integer>();
                for (int i = 0; i < 12; i++) {
                    mapDay.put(i * 2, 0);
                }
                for (TradeAppVo tradeAppVo : appList) {
                    int requestNum = tradeAppVo.getRequestNum();
                    int hour = (int) Math.floor(Integer.valueOf(tradeAppVo.getRequestDate()) / 2);
                    mapDay.put(hour * 2, mapDay.get(hour * 2) + requestNum);
                }
                for (Integer hour : mapDay.keySet()) {
                    TradeAppVo appVo = new TradeAppVo();
                    Integer num = mapDay.get(hour);
                    appVo.setRequestDate(String.valueOf(hour) + ":00");
                    appVo.setRequestNum(num);
                    dataList.add(appVo);
                }
                break;
            case "week": //下一个case也执行
                flag = "week";
            case "month":
                List<String> list = new LinkedList<>();
                int len = 0;
                if (flag.equals("week")) {
                    list = DateUtils.getWeekEveryDays(nowDate);
                    len = list.size();
                } else {
                    list = DateUtils.getMonthEveryDays(nowDate);
                    len = list.size();
                }
                gatewayLogDayVO.setBeginDate(list.get(0));
                gatewayLogDayVO.setEndDate(list.get(list.size() - 1));
                IPage<ApiVO> req_1 = new Page<ApiVO>();
                req_1.setCurrent(1);
                req_1.setSize(99999999); // 不分页，查所有

                if (sysProlist != null && sysProlist.size() > 0) {
                    // 产品下API统计
                    for (Product proVO : sysProlist) {
                        ApiVO apiVO_1 = new ApiVO();
                        apiVO_1.setOpcProductId(proVO.getId());
                        IPage<ApiVO> page_1 = apiService.selectProductApiList(req_1, apiVO_1);
                        if (page_1.getRecords() != null && page_1.getRecords().size() > 0) {
                            for (ApiVO vo : page_1.getRecords()) {
                                if (vo != null && vo.getApiCode() != null) {
                                    gatewayLogDayVO.setOpcApiCode(vo.getApiCode());
                                }
                                List<TradeAppVo> oneApiList = gatewayLogDayService.selectCountByDate(gatewayLogDayVO);
                                if (oneApiList != null && oneApiList.size() > 0) {
                                    for (TradeAppVo tVo : oneApiList) {
                                        appList.add(tVo);
                                    }
                                }
                            }
                        }
                    }
                }

                Map<String, Integer> mapWeek = new LinkedHashMap<String, Integer>(); // 返回
                for (int i = 0; i < len; i++) {
                    mapWeek.put(list.get(i), 0);
                }
                for (String key : mapWeek.keySet()) {
                    TradeAppVo appVo = new TradeAppVo();
                    appVo.setRequestDate(key);
                    appVo.setRequestNum(0);
                    for (TradeAppVo data : appList) {
                        if (key.equals(data.getRequestDate())) {
                            appVo.setRequestNum(appVo.getRequestNum() + data.getRequestNum());
                        }
                    }
                    dataList.add(appVo);
                }
                break;
            case "year":
                String beginDate = nowDate.substring(0, 4) + "0101";
                String endDate = nowDate.substring(0, 4) + "1231";
                gatewayLogDayVO.setBeginDate(beginDate);
                gatewayLogDayVO.setEndDate(endDate);

                IPage<ApiVO> req_2 = new Page<ApiVO>();
                req_2.setCurrent(1);
                req_2.setSize(99999999); // 不分页，查所有

                if (sysProlist != null && sysProlist.size() > 0) {
                    // 产品下API统计
                    for (Product proVO : sysProlist) {
                        ApiVO apiVO_2 = new ApiVO();
                        apiVO_2.setOpcProductId(proVO.getId());
                        IPage<ApiVO> page_2 = apiService.selectProductApiList(req_2, apiVO_2);
                        if (page_2.getRecords() != null && page_2.getRecords().size() > 0) {
                            for (ApiVO vo : page_2.getRecords()) {
                                gatewayLogDayVO.setOpcApiCode(vo.getApiCode());
                                List<TradeAppVo> oneApiList = gatewayLogDayService.selectCountByYear(gatewayLogDayVO);
                                if (oneApiList != null && oneApiList.size() > 0) {
                                    for (TradeAppVo tVo : oneApiList) {
                                        appList.add(tVo);
                                    }
                                }
                            }
                        }
                    }
                }

                Map<String, Integer> mapYear = new LinkedHashMap<String, Integer>(); // 返回
                for (int i = 1; i <= 12; i++) {
                    mapYear.put(String.valueOf(i), 0);
                }
                for (String key : mapYear.keySet()) {
                    TradeAppVo appVo = new TradeAppVo();
                    appVo.setRequestDate(key);
                    appVo.setRequestNum(0);
                    for (TradeAppVo app : appList) {
                        app.setRequestDate(String.valueOf(Integer.parseInt(app.getRequestDate())));
                        if (key.equals(app.getRequestDate())) {
                            appVo.setRequestNum(appVo.getRequestNum() + app.getRequestNum());
                        }
                    }
                    dataList.add(appVo);
                }
                break;
            default:
                break;
        }
        return R.data(dataList);
    }

    /**
     * @param type
     * @param appApiViewVo
     * @return org.springblade.core.tool.api.R<com.dhcc.bpm.modules.log.vo.AppApiViewVo>
     * @Description 某一机构/应用下数据统计
     * @Author xiafayu
     * @Date 2020/2/24 15:21
     **/
    @GetMapping("/appCount/{type}")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "某一应用下数据统计", notes = "传入AppApiVo")
    @Log(title = "某一应用下数据统计", businessType = BusinessType.SELECT)
    public R<AppApiViewVo> appCount(@PathVariable("type") String type, AppApiViewVo appApiViewVo) {
        AppApiViewVo app = gatewayLogDayService.countAppData(appApiViewVo); // 统计响应次数、成功次数、失败次数

        // 求失败率
        String failRate = "0.00";
        if (app.getRequestNum() != 0) {
            DecimalFormat df = new DecimalFormat("0.00");//格式化小数
            double value = (double) app.getFailRequestNum() / app.getRequestNum() * 100;
            failRate = df.format(value);//返回的是String类型
        }
        app.setFailRate(failRate);
        return R.data(app);
    }


    /**
     * @param appApiViewVo
     * @param query
     * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage < com.dhcc.bpm.modules.log.vo.AppApiViewVo>>
     * @Description (机构下 / 所有)应用集合展示
     * @Author xiafayu
     * @Date 2020/2/24 15:21
     **/
    @GetMapping("/appList")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "应用集合展示", notes = "传入AppApiVo")
    @Log(title = "应用集合统计展示", businessType = BusinessType.SELECT)
    public R<IPage<AppRankVo>> appList(AppApiViewVo appApiViewVo, Query query) {
        AppRankVo appRankVo = new AppRankVo();
        appRankVo.setAppIdNotNull("true"); // app_id 不为空
        appRankVo.setRankFlag("true");
        appRankVo.setStatus(1); // 	审批状态  1--已通过
        if (!StringUtils.isEmpty(appApiViewVo.getEnv())) {
            appRankVo.setEnvStr(appApiViewVo.getEnv());
        }
        if (!StringUtils.isEmpty(appApiViewVo.getId())) {
            appRankVo.setOrgaId(appApiViewVo.getId());
        }
        if (!StringUtils.isEmpty(appApiViewVo.getAppId())) {
            appRankVo.setAppId(appApiViewVo.getAppId());
        }
        String startDate = "", endDate = "";
        if (appApiViewVo.getRequestDate() != null && appApiViewVo.getRequestDate().length() > 0) { // 传入日期处理
            startDate = appApiViewVo.getRequestDate().split(",")[0];
            endDate = appApiViewVo.getRequestDate().split(",")[1];
            appRankVo.setBegDate(startDate);
            appRankVo.setEndDate(endDate);
        }
        IPage<AppRankVo> appRankVoList = gatewayLogDayService.countAppNum(Condition.getPage(query), appRankVo);
        if (appRankVoList.getRecords() != null && appRankVoList.getRecords().size() > 0) {
            for (AppRankVo appRank : appRankVoList.getRecords()) {
                DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                // 失败率
                String failRate = "0.00";
                if (appRank.getNum() != 0) {
                    double value = (double) appRank.getFailNum() / appRank.getNum() * 100;
                    failRate = df.format(value);//返回的是String类型
                }

                // 平均响应时间
                double avgResTime = 0.00;
                if (appRank.getLineNum() != 0) {
                    avgResTime = Double.valueOf(df.format(appRank.getResponseTime() / appRank.getLineNum()));
                }

                appRank.setFailRate(failRate);
                appRank.setResponseTime(avgResTime);
            }
        }
        return R.data(appRankVoList);
    }

    /**
     * @param appApiViewVo
     * @param query
     * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage < com.dhcc.bpm.modules.log.vo.AppApiViewVo>>
     * @Description 某一机构/应用下接口集合展示
     * @Author xiafayu
     * @Date 2020/2/24 15:21
     **/
    @GetMapping("/apiList")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "某一机构/应用下接口集合展示", notes = "传入AppApiVo")
    @Log(title = "api集合统计展示", businessType = BusinessType.SELECT)
    public R<IPage<AppApiViewVo>> apiList(AppApiViewVo appApiViewVo, Query query) {
        IPage<AppApiViewVo> pages = null;
        if ("hour".equals(appApiViewVo.getTimeType())) {
            String[] time = DateUtils.getDateTimeAddOneHour(-1);
            appApiViewVo.setStartTime(time[0]);
            appApiViewVo.setEndTime(time[1]);
        } else if ("day".equals(appApiViewVo.getTimeType())) {
            appApiViewVo.setStartTime(DateUtils.date());
            appApiViewVo.setEndTime(DateUtils.date());
        } else if ("week".equals(appApiViewVo.getTimeType())) {
            appApiViewVo.setStartTime(DateUtils.getPastDate(7, "yyyyMMdd"));
            appApiViewVo.setEndTime(DateUtils.date());
        } else if ("month".equals(appApiViewVo.getTimeType())) {
            appApiViewVo.setStartTime(DateUtils.getLastMonth(-1, "yyyyMMdd"));
            appApiViewVo.setEndTime(DateUtils.date());
        }
        if (appApiViewVo != null && appApiViewVo.getAppId() != null && appApiViewVo.getAppId().equals("-1")) { // 查询产品下api
            appApiViewVo.setAppId(null);
            if ("hour".equals(appApiViewVo.getTimeType())) {
                pages = gatewayLogDayService.selectProApiNumHour(Condition.getPage(query), appApiViewVo);
            } else {
                pages = gatewayLogDayService.selectProApiNum(Condition.getPage(query), appApiViewVo);
            }
        } else { // 查询应用下api
            pages = gatewayLogDayService.selectAppApiNum(Condition.getPage(query), appApiViewVo);
        }

        if (pages.getRecords() != null && pages.getRecords().size() > 0) {
            for (AppApiViewVo vo : pages.getRecords()) {
                // 失败率
                String failRate = "0.00";
                DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                if (vo.getRequestNum() != 0) {
                    double value = (double) vo.getFailRequestNum() / vo.getRequestNum() * 100;
                    failRate = df.format(value);//返回的是String类型
                }
                // 平均响应时间
                double avgResTime = 0.00;
                if (vo.getLineNum() != 0) {
                    avgResTime = Double.valueOf(df.format(vo.getResponseTime() / vo.getLineNum()));
                }
                vo.setFailRate(failRate);
                vo.setResponseTime(avgResTime);
            }
        }
        return R.data(pages);
    }

    /**
     * @param appApiViewVo
     * @return org.springblade.core.tool.api.R<java.util.List < com.dhcc.bpm.modules.log.vo.AppApiViewVo>>
     * @Description 某一接口下数据图表统计
     * @Author xiafayu
     * @Date 2020/2/24 15:25
     **/
    @GetMapping("/apiChartData")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "某一接口下数据图表统计", notes = "传入AppApiVo")
    @Log(title = "api数据图表统计", businessType = BusinessType.SELECT)
    public R<List<AppApiViewVo>> apiChartData(AppApiViewVo appApiViewVo) {
        List<AppApiViewVo> resList = new ArrayList<AppApiViewVo>();
        String nowDate = DateUtils.dateTime();
        String type = appApiViewVo.getDateType();
        List<String> list = new ArrayList<>();
        List<AppApiViewVo> queryList = new ArrayList<>();
        Map<String, Integer> allMap = new LinkedHashMap<String, Integer>(); // 返回
        String nowTime = DateUtils.dateTimeNow().substring(8, 10);
        String[] time = DateUtils.getDateTimeAddOneHour(-1);
        switch (type) {
            case "minute":
                appApiViewVo.setRequestDate(nowDate.substring(0, 8));
//                appApiViewVo.setRequestTime(nowTime);
                appApiViewVo.setStartTime(time[0].substring(8, 12));
                appApiViewVo.setEndTime(time[1].substring(8, 12));
                int val = Integer.valueOf(time[0].substring(10, 12));
                boolean flag = false;
                for (int i = 0; i < 60; i++) {
//                    allMap.put(String.valueOf(i), 0);
                    if (val < 60) {
                        if (flag) {
                            if (val < 10) {
                                allMap.put(time[1].substring(8, 10) + 0 + val, 0);
                            } else {
                                allMap.put(time[1].substring(8, 10) + val, 0);
                            }
                        } else {
                            if (val < 10) {
                                allMap.put(time[0].substring(8, 10) + 0 + val, 0);
                            } else {
                                allMap.put(time[0].substring(8, 10) + val, 0);
                            }
                        }
                    } else {
                        val = 0;
                        flag = true;
                        allMap.put(time[1].substring(8, 10) + 0 + val, 0);
                    }
                    val = val + 1;
                }
                queryList = gatewayLogMinuteService.apiChartByMinute(appApiViewVo);
                break;
            case "day":
                appApiViewVo.setRequestDate(nowDate.substring(0, 8));
                for (int i = 0; i < 24; i++) {
                    allMap.put(String.valueOf(i), 0);
                }
                queryList = gatewayLogMinuteService.apiChartDataByMinute(appApiViewVo);
                break;
            case "week":
                try {
//					list = DateUtils.getWeekEveryDays(nowDate);
                    list = DateUtils.getLastDays(nowDate.substring(0, 8), 7);
                } catch (Exception e) {
                    logger.error("获取近七日日期失败");
                }
                appApiViewVo.setBegDate(list.get(list.size() - 1));
                appApiViewVo.setEndDate(list.get(0));
                int len = list.size();
                if (appApiViewVo != null && appApiViewVo.getAppId() != null && appApiViewVo.getAppId().equals("-1")) { // 查询产品下api
                    appApiViewVo.setAppId(null);
                }
                queryList = gatewayLogDayService.apiChartData(appApiViewVo);
                for (int i = 0; i < len; i++) {
                    allMap.put(list.get(len - i - 1), 0);
                }
                break;
            case "month":
                try {
//				list= DateUtils.getMonthEveryDays(appApiViewVo.getMonthDate()+"01");
                    list = DateUtils.getLastDays(nowDate.substring(0, 8), 30);
                } catch (Exception e) {
                    logger.error("获取近30天日期失败");
                }
                appApiViewVo.setBegDate(list.get(list.size() - 1));
                appApiViewVo.setEndDate(list.get(0));
                int lenth = list.size();
                if (appApiViewVo != null && appApiViewVo.getAppId() != null && appApiViewVo.getAppId().equals("-1")) { // 查询产品下api
                    appApiViewVo.setAppId(null);
                }
                queryList = gatewayLogDayService.apiChartData(appApiViewVo);
                for (int i = 0; i < lenth; i++) {
                    allMap.put(list.get(lenth - i - 1), 0);
                }
                break;
            case "year":
                String beginDate = nowDate.substring(0, 4) + "0101";
                String endDate = nowDate.substring(0, 4) + "1231";
                appApiViewVo.setBegDate(beginDate);
                appApiViewVo.setEndDate(endDate);
                for (int i = 0; i < 12; i++) {
                    allMap.put(String.valueOf(i), 0);
                }
                break;
            default:
                break;
        }

        for (String key : allMap.keySet()) {
            AppApiViewVo api = new AppApiViewVo();
            api.setDateType(type);
            if (type.equals("day") || type.equals("minute")) {
                api.setRequestDate(nowDate);
                api.setRequestTime(key);
                if (type.equals("minute")) {
                    api.setRequestTime(key);
                }
                api.setRequestNum(0L);
                api.setRequestConsume("0");
                api.setFailRequestNum(0L);
                api.setSuccessNum(0L);
                api.setFailRate("0.00");
                if (queryList != null && queryList.size() > 0) {

                    for (AppApiViewVo vo : queryList) {
                        String key2 = key;
                        if (Integer.parseInt(key2) < 10) {
                            key2 = "0" + key2;
                        }
                        if (key2.equals(vo.getRequestTime())) {
                            api.setRequestNum(vo.getRequestNum());
                            api.setSuccessNum(vo.getSuccessNum());
                            api.setRequestConsume(vo.getRequestConsume());
                            api.setFailRequestNum(vo.getFailRequestNum());
                            String failRate = "0.00";
                            String requestConsume = "0";
                            if (vo.getRequestNum() != 0) {
                                DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                                double value = (double) vo.getSuccessNum() / vo.getRequestNum() * 100;
                                failRate = df.format(value);//返回的是String类型
                                double reqCon = (double) Double.valueOf(vo.getRequestConsume()) / vo.getRequestNum();
                                requestConsume = df.format(reqCon);
                            }
                            api.setFailRate(failRate);
                            api.setRequestConsume(requestConsume);
                            break;
                        }
                    }
                }
            } else if (type.equals("week") || type.equals("month")) {
                api.setRequestDate(key);
                api.setRequestNum(0L);
                api.setRequestConsume("0");
                api.setFailRequestNum(0L);
                api.setSuccessNum(0L);
                api.setFailRate("0.00");
                if (queryList != null && queryList.size() > 0) {
                    for (AppApiViewVo vo : queryList) {
                        if (key.equals(vo.getRequestDate())) {
                            api.setRequestNum(vo.getRequestNum());
                            api.setSuccessNum(vo.getSuccessNum());
                            api.setResponseTime(vo.getResponseTime());
                            api.setFailRequestNum(vo.getFailRequestNum());
                            // api 平均耗时
                            api.setRequestConsume(vo.getRequestConsume());
                            String failRate = "0.00";
                            String requestConsume = vo.getRequestConsume() == null ? "0" : vo.getRequestConsume();
                            if (vo.getRequestNum() != 0) {
                                DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                                double value = (double) vo.getSuccessNum() / vo.getRequestNum() * 100;
                                failRate = df.format(value);//返回的是String类型
                                if (vo.getRequestConsume() != null && vo.getRequestNum() != null) {
                                    double reqCon = (double) Double.valueOf(vo.getRequestConsume()) / vo.getRequestNum();// * 100
                                    requestConsume = df.format(reqCon);
                                }
                            }
                            api.setFailRate(failRate);
                            api.setRequestConsume(requestConsume);
                            break;
                        }
                    }
                }
            }
            resList.add(api);
        }
        List<AppApiViewVo> resMinuteList = new ArrayList<AppApiViewVo>();
        if (type.equals("minute")) {
            // 定义每隔五分钟统计一次
            int n = 3;
            for (int i = 0; i < resList.size(); i = i + 3) {
                AppApiViewVo api = new AppApiViewVo();
                Long reqNum = 0L;
                Double reqConsume = 0.0;
                Long failNum = 0L;
                Long sucNUm = 0L;
                for (int j = 0; j < n; j++) {
                    reqNum = reqNum + resList.get(i + j).getRequestNum();
                    reqConsume = reqConsume + Double.valueOf(resList.get(i + j).getRequestConsume());
                    failNum = failNum + resList.get(i + j).getFailRequestNum();
                    sucNUm = sucNUm + resList.get(i + j).getSuccessNum();
                }
//                if (i < 10) {
//                    api.setRequestTime(nowTime + ":0" + i);
//                } else {
//                    api.setRequestTime(nowTime + ":" + i);
//                }
                api.setRequestTime(resList.get(i).getRequestTime().substring(0, 2) + ":" + resList.get(i).getRequestTime().substring(2, 4));
                api.setRequestNum(reqNum);
                api.setRequestConsume(reqConsume.toString());
                api.setFailRequestNum(failNum);
                api.setSuccessNum(sucNUm);
                String failRate = "0.00";
                if (api.getRequestNum() != 0) {
                    DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                    double value = (double) api.getSuccessNum() / api.getRequestNum() * 100;
                    failRate = df.format(value);//返回的是String类型
                }
                api.setFailRate(failRate);
                api.setDateType(type);
                resMinuteList.add(api);
            }
            return R.data(resMinuteList);
        } else {
            return R.data(resList);
        }
    }

    /**
     * @param gatewayLogMinute
     * @return org.springblade.core.tool.api.R<com.dhcc.bpm.modules.log.vo.TodayCount>
     * @Description 日交易量 、日成功率、日成功数（首页2，3块长方块）
     * @Author xiafayu
     * @Date 2020/2/24 15:25
     **/
    @GetMapping("/tradingVolume")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "机构交易量排行", notes = "传入gatewayLogMinuteVO")
    @Log(title = "日交易量统计", businessType = BusinessType.SELECT)
    public R<TodayCount> tradingVolume(GatewayLogMinute gatewayLogMinute) {
        String nowDate = DateUtils.dateTime();
        gatewayLogMinute.setRequestDate(nowDate);
        TradeVolumnVo res = gatewayLogMinuteService.tradingVolume(gatewayLogMinute);

        // 成功率
        String rate = "0.00";
        TodayCount todayCount = new TodayCount();
        String numS = "0", successNumS = "0";

        if (res != null && res.getNum() != null && res.getNum() != 0) {
            DecimalFormat df = new DecimalFormat("#,###");
            numS = df.format(res.getNum());
            successNumS = df.format(res.getSuccessNum());

            DecimalFormat df1 = new DecimalFormat("0.00");//格式化小数
            rate = df1.format((float) res.getSuccessNum() / res.getNum() * 100);//返回的是String类型
        }

        todayCount.setNum(numS);
        todayCount.setSuccessNum(successNumS);
        todayCount.setRate(rate);
        return R.data(todayCount);
    }

    /**
     * @param vo
     * @param env
     * @return long
     * @Description 获取当日产品交易量（minute 表）
     * @Author xiafayu
     * @Date 2020/2/24 15:25
     **/
    private long gainProductNumToday(AppApiViewVo vo, String env) {
        long num = 0;
        vo.setEnv(env);
        List<AppApiViewVo> todayList = gatewayLogMinuteService.countProductByDate(vo);
        if (todayList != null && todayList.size() > 0 && todayList.get(0) != null && todayList.get(0).getRequestNum() != null) {
            num = todayList.get(0).getRequestNum();
        }
        return num;
    }

    /**
     * @param vo
     * @param env
     * @return long
     * @Description 获取某日产品交易量（day 表）
     * @Author xiafayu
     * @Date 2020/2/24 15:26
     **/
    private long gainProductNumOneDay(ProductRankVo vo, String env) {
        long num = 0;
        vo.setEnv(env);
        List<ProductRankVo> oneDayList = gatewayLogDayService.countProductByDate(vo);
        if (oneDayList != null && oneDayList.size() > 0 && oneDayList.get(0) != null && oneDayList.get(0).getNum() != null) {
            num = oneDayList.get(0).getNum();
        }
        return num;
    }

    /**
     * @param gatewayLogMinute
     * @param env
     * @return java.lang.Integer
     * @Description 获取当日交易量
     * @Author xiafayu
     * @Date 2020/2/24 15:26
     **/
    private Long gainTodayRequestNum(GatewayLogMinute gatewayLogMinute, String env) {
        Long num = 0L;
        String nowDate = DateUtils.dateTime();

        gatewayLogMinute.setEnv(env);
        gatewayLogMinute.setRequestDate(nowDate.substring(0, 8));
        TradeVolumnVo tradeVolumnVo = gatewayLogMinuteService.tradingVolume(gatewayLogMinute);
        if (tradeVolumnVo != null && tradeVolumnVo.getNum() != null) {
            num = tradeVolumnVo.getNum();
        }
        return num;
    }


    /**
     * @param tpsEntity
     * @return org.springblade.core.tool.api.R
     * @Description 获取API数量、TPS、峰值
     * @Author xiafayu
     * @Date 2020/2/24 15:27
     **/
    @PostMapping("/getRateStatistics")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "获取API数量、TPS、峰值", notes = "传入ids")
    @ApiLog("获取API数量、TPS、峰值")
    @Log(title = "获取API数量、TPS、峰值", businessType = BusinessType.SELECT)
    public R getRateStatistics(TpsEntity tpsEntity) {
        JSONObject json = new JSONObject();
        AlarmNoticeVO alarmNotice = new AlarmNoticeVO();
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        //获取环境类型
        String env = tpsEntity.getEnv();
        //请求类型
        String type = tpsEntity.getType();
        String requestDate = DateUtils.dateTime();
        //查询结果延迟3秒
        String requestTime = String.valueOf(Long.valueOf(DateUtils.getDateTime()) - 3);
        String tpsKey = GatewayLogUtil.getTpsKey(env, requestDate, requestTime);
        String numKey = GatewayLogUtil.getNumKey(env, requestDate);
        String apiTpsKey = "";
        String apiNumKey = "";

        alarmNotice.setRequestDate(requestDate);
        alarmNotice.setAlarmEnv(env);
        switch (type) {
            //首页概览统计
            case "1":
                json.put("requestNum", opsForValue.get("requestTps:" + tpsKey) == null ? "0" : opsForValue.get("requestTps:" + tpsKey));
                Long requestTps = Long.valueOf(opsForValue.get("requestNum:" + numKey) == null ? "0" : opsForValue.get("requestNum:" + numKey));
                json.put("requestTps", requestTps);
                json.put("alarmNum", alarmNoticeService.getAlarmNotice(alarmNotice));
                if (opsForValue.get("requestPeak:all") == null) {
                    opsForValue.set("requestPeak:all", String.valueOf(requestTps));
                    json.put("requestPeak", requestTps);
                } else {
                    if (Long.valueOf(opsForValue.get("requestPeak:all")) > requestTps) {
                        json.put("requestPeak", opsForValue.get("requestPeak:all"));
                    } else {
                        json.put("requestPeak", requestTps);
                    }
                }
                json.put("linkNum", "");
                return R.data(json);
            //系统管理
            case "2":
                Long tps = 0L;
                Long num = 0L;
                Integer sysNoticeNum = 0;
                Long sysId = tpsEntity.getSysId();
                List<BaseProduct> prodList = baseProductService.selectBySysId(sysId);
                for (BaseProduct baseProduct : prodList) {
                    List<String> listNew = getApiCodeBybaseProductId(baseProduct.getId());
                    for (int i = 0; i < listNew.size(); i++) {
                        apiTpsKey = "requestTps:" + GatewayLogUtil.getApiTpsKey(env, requestDate, requestTime, listNew.get(i));
                        apiNumKey = "requestNum:" + GatewayLogUtil.getApiNumKey(env, requestDate, listNew.get(i));
                        tps = tps + Long.valueOf(opsForValue.get(apiTpsKey) == null ? "0" : opsForValue.get(apiTpsKey));
                        num = num + Long.valueOf(opsForValue.get(apiNumKey) == null ? "0" : opsForValue.get(apiNumKey));
                        alarmNotice.setApiCode(listNew.get(i));
                        sysNoticeNum = sysNoticeNum + alarmNoticeService.getAlarmNotice(alarmNotice);
                    }
                }
                json.put("requestNum", num);
                json.put("requestTps", tps);
                json.put("alarmNum", sysNoticeNum);
                if (opsForValue.get("requestPeak:" + sysId) == null) {
                    opsForValue.set("requestPeak:" + sysId, String.valueOf(tps));
                    json.put("requestPeak", tps);
                } else {
                    if (Long.valueOf(opsForValue.get("requestPeak:" + sysId)) > tps) {
                        json.put("requestPeak", opsForValue.get("requestPeak:" + sysId));
                    } else {
                        json.put("requestPeak", tps);
                    }
                }
                json.put("linkNum", "");
                return R.data(json);
            //基础产品
            case "3":
                Long baseProductTps = 0L;
                Long baseProductNum = 0L;
                Integer noticeNum = 0;
                List<String> listNew = getApiCodeBybaseProductId(tpsEntity.getBaseProductId());
                for (int i = 0; i < listNew.size(); i++) {
                    apiTpsKey = "requestTps:" + GatewayLogUtil.getApiTpsKey(env, requestDate, requestTime, listNew.get(i));
                    apiNumKey = "requestNum:" + GatewayLogUtil.getApiNumKey(env, requestDate, listNew.get(i));
                    baseProductTps = baseProductTps + Long.valueOf(opsForValue.get(apiTpsKey) == null ? "0" : opsForValue.get(apiTpsKey));
                    baseProductNum = baseProductNum + Long.valueOf(opsForValue.get(apiNumKey) == null ? "0" : opsForValue.get(apiNumKey));
                    alarmNotice.setApiCode(listNew.get(i));
                    noticeNum = noticeNum + alarmNoticeService.getAlarmNotice(alarmNotice);
                }
                json.put("requestNum", baseProductNum);
                json.put("requestTps", baseProductTps);
                json.put("alarmNum", noticeNum);
                if (opsForValue.get("requestPeak:" + tpsEntity.getBaseProductId()) == null) {
                    opsForValue.set("requestPeak:" + tpsEntity.getBaseProductId(), String.valueOf(baseProductTps));
                    json.put("requestPeak", baseProductTps);
                } else {
                    if (Long.valueOf(opsForValue.get("requestPeak:" + tpsEntity.getBaseProductId())) > baseProductTps) {
                        json.put("requestPeak", opsForValue.get("requestPeak:" + tpsEntity.getBaseProductId()));
                    } else {
                        json.put("requestPeak", baseProductTps);
                    }
                }
                json.put("linkNum", "");
                return R.data(json);
            //api发布
            case "4":
                com.dhcc.bpm.modules.api.entity.Api api = apiService.getById(tpsEntity.getApiId());
                apiTpsKey = "requestTps:" + GatewayLogUtil.getApiTpsKey(env, requestDate, requestTime, api.getApiCode());
                apiNumKey = "requestNum:" + GatewayLogUtil.getApiNumKey(env, requestDate, api.getApiCode());
                json.put("requestNum", Long.valueOf(opsForValue.get(apiNumKey) == null ? "0" : opsForValue.get(apiNumKey)));
                Long apiTps = Long.valueOf(opsForValue.get(apiTpsKey) == null ? "0" : opsForValue.get(apiTpsKey));
                json.put("requestTps", apiTps);

                alarmNotice.setApiCode(api.getApiCode());
                json.put("alarmNum", alarmNoticeService.getAlarmNotice(alarmNotice));
                if (opsForValue.get("requestPeak:" + tpsEntity.getApiId()) == null) {
                    opsForValue.set("requestPeak:" + tpsEntity.getApiId(), String.valueOf(apiTps));
                    json.put("requestPeak", apiTps);
                } else {
                    if (Long.valueOf(opsForValue.get("requestPeak:" + tpsEntity.getApiId())) > apiTps) {
                        json.put("requestPeak", opsForValue.get("requestPeak:" + tpsEntity.getApiId()));
                    } else {
                        json.put("requestPeak", apiTps);
                    }
                }
                json.put("linkNum", "");
                return R.data(json);
            //应用产品
            case "5":
                Long productTps = 0L;
                Long productNum = 0L;
                Integer prodNoticeNum = 0;
                List<com.dhcc.bpm.modules.api.entity.Api> prodApi = apiService.getProdApiByProductId(tpsEntity.getProductId());
                for (com.dhcc.bpm.modules.api.entity.Api opcApi : prodApi) {
                    apiTpsKey = "requestTps:" + GatewayLogUtil.getApiTpsKey(env, requestDate, requestTime, opcApi.getApiCode());
                    apiNumKey = "requestNum:" + GatewayLogUtil.getApiNumKey(env, requestDate, opcApi.getApiCode());
                    productTps = productTps + Long.valueOf(opsForValue.get(apiTpsKey) == null ? "0" : opsForValue.get(apiTpsKey));
                    productNum = productNum + Long.valueOf(opsForValue.get(apiNumKey) == null ? "0" : opsForValue.get(apiNumKey));
                    alarmNotice.setApiCode(opcApi.getApiCode());
                    prodNoticeNum = prodNoticeNum + alarmNoticeService.getAlarmNotice(alarmNotice);
                }
                json.put("requestNum", productNum);
                json.put("requestTps", productTps);
                json.put("alarmNum", prodNoticeNum);
                if (opsForValue.get("requestPeak:" + tpsEntity.getProductId()) == null) {
                    opsForValue.set("requestPeak:" + tpsEntity.getProductId(), String.valueOf(productTps));
                    json.put("requestPeak", productTps);
                } else {
                    if (Long.valueOf(opsForValue.get("requestPeak:" + tpsEntity.getProductId())) > productTps) {
                        json.put("requestPeak", opsForValue.get("requestPeak:" + tpsEntity.getProductId()));
                    } else {
                        json.put("requestPeak", productTps);
                    }
                }
                json.put("linkNum", "");
                return R.data(json);
            default:
                Long allTps = Long.valueOf(opsForValue.get("requestNum:" + numKey) == null ? "0" : opsForValue.get("requestNum:" + numKey));
                json.put("requestNum", opsForValue.get("requestTps:" + tpsKey) == null ? "0" : opsForValue.get("requestTps:" + tpsKey));
                json.put("requestTps", allTps);
                json.put("alarmNum", alarmNoticeService.getAlarmNotice(alarmNotice));
                if (opsForValue.get("requestPeak:all") == null) {
                    opsForValue.set("requestPeak:all", String.valueOf(allTps));
                    json.put("requestPeak", allTps);
                } else {
                    if (Long.valueOf(opsForValue.get("requestPeak:all")) > allTps) {
                        json.put("requestPeak", opsForValue.get("requestPeak:all"));
                    } else {
                        json.put("requestPeak", allTps);
                    }
                }
                json.put("linkNum", "");
                return R.data(json);
        }
    }


    /**
     * @param tpsEntity
     * @return org.springblade.core.tool.api.R
     * @Description 获取API数量、TPS、峰值
     * @Author xiafayu
     * @Date 2020/2/24 15:27
     **/
    @PostMapping("/getStatistics")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "获取API数量、TPS、峰值", notes = "传入ids")
    @ApiLog("获取API数量、TPS、峰值")
    @Log(title = "获取API数量、TPS、峰值", businessType = BusinessType.SELECT)
    public R getStatistics(@RequestBody TpsEntity tpsEntity) {
        JSONObject json = new JSONObject();
        AlarmNoticeVO alarmNotice = new AlarmNoticeVO();
        GatewayLog gatewayLog = new GatewayLog();
        //获取环境类型
        String env = tpsEntity.getEnv();
        //请求类型
        String type = tpsEntity.getType();
        String requestDate = DateUtils.dateTime();
        String date = DateUtils.dateSecond(-3);
        gatewayLog.setEnvType(env);

        alarmNotice.setRequestDate(requestDate);
        alarmNotice.setAlarmEnv(env);
        List<String> apiList = new ArrayList<>();
        ValueOperations<String, String> redis = stringRedisTemplate.opsForValue();

        // 告警数量统计
        AlarmStatistic alarmStatistic = new AlarmStatistic();

        switch (type) {
            //首页概览统计
            case "1":
                GatewayLog gatewayLogCount = gatewayLog;
                CompletableFuture<Integer> requestNum = CompletableFuture.supplyAsync(() -> gatewayLogService.queryCount(gatewayLogCount));
                CompletableFuture<Integer> alarmNum = CompletableFuture.supplyAsync(() -> alarmStatisticService.getAlarmCount(alarmStatistic));
                CompletableFuture<Long> tps = CompletableFuture.supplyAsync(() -> getAllTps(date));
                CompletableFuture<Long> requestPeak = CompletableFuture.supplyAsync(() -> tpsService.queryTpsByDate(date.substring(0, 8), null));
                //计算·日交易量

                CompletableFuture<TodayRequestNum> todayRequestNum = CompletableFuture.supplyAsync(() -> {
                    return gatewayLogService.queryToDayCount(gatewayLog);
                });

                CompletableFuture.allOf(requestNum, alarmNum, tps, requestPeak).join();
                json.put("requestNum", requestNum.join());
                json.put("alarmNum", alarmNum.join());
                json.put("requestTps", tps.join());
                long reqPeak = requestPeak.join();
                if (tps.join() > requestPeak.join()) {
                    reqPeak = tps.join();
                }

                json.put("requestPeak", reqPeak + "");
                json.put("requestPeakTime", date);
                json.put("linkNum", getLinkNum());
                TodayRequestNum todayCount = todayRequestNum.join();
                json.put("requestDayNum", todayCount == null ? 0 : todayCount.getRequestNum());
                json.put("requestDaySuccessNum", todayCount == null ? 0 : todayCount.getSuccessNum());
                return R.data(json);
            //系统管理
            case "2":
                Long sysTps = 0L;
                Long num = 0L;
                Long daynum = 0L;
                Long daysuccnum = 0L;
                //Integer sysNoticeNum = 0;
                Long sysId = tpsEntity.getSysId();
                List<BaseProduct> prodList = baseProductService.selectBySysId(sysId);
                for (BaseProduct baseProduct : prodList) {
                    List<String> listNew = getApiCodeBybaseProductId(baseProduct.getId());
                    for (int i = 0; i < listNew.size(); i++) {
                        sysTps = sysTps + getTpsByApiCode(listNew.get(i), date);

                        gatewayLog.setOpcApiCode(listNew.get(i));
                        num = num + gatewayLogService.queryCount(gatewayLog);
                        //计算·日交易量
                        gatewayLog.setRequestDate(DateUtils.date());
                        TodayRequestNum sysTodayCount = gatewayLogService.queryToDayCount(gatewayLog);
                        if (null != sysTodayCount) {
                            daynum = daynum + sysTodayCount.getRequestNum();
                            daysuccnum = daysuccnum + sysTodayCount.getSuccessNum();
                        }

                        alarmNotice.setApiCode(listNew.get(i));
                    }
                    apiList.addAll(listNew);
                }
                json.put("requestNum", num);
                json.put("requestDayNum", daynum);
                json.put("requestDaySuccessNum", daysuccnum);

                Sys opcSys = sysService.selectBySysId(sysId);
                alarmStatistic.setSystemNo(opcSys.getSysCode());
                json.put("alarmNum", alarmStatisticService.getAlarmCount(alarmStatistic));

                long sysRequestPeak = tpsService.queryTpsByDate(date.substring(0, 8), apiList);
                if (sysTps > sysRequestPeak) {
                    sysRequestPeak = sysTps;
                }
                json.put("requestTps", sysTps);
                json.put("requestPeak", sysRequestPeak);
                json.put("requestPeakTime", date);
                json.put("linkNum", getLinkNum());
                return R.data(json);
            //基础产品
            case "3":
                Long baseProductTps = 0L;
                Long baseProductNum = 0L;
                Long bdaynum = 0L;
                Long bdaysuccnum = 0L;
                Integer noticeNum = 0;
                List<String> listNew = getApiCodeBybaseProductId(tpsEntity.getBaseProductId());
                for (int i = 0; i < listNew.size(); i++) {
                    gatewayLog.setOpcApiCode(listNew.get(i));
                    baseProductNum = baseProductNum + gatewayLogService.queryCount(gatewayLog);
                    //计算·日交易量
                    gatewayLog.setRequestDate(DateUtils.date());
                    TodayRequestNum baseProductTodayCount = gatewayLogService.queryToDayCount(gatewayLog);

                    if (null != baseProductTodayCount) {
                        bdaynum = bdaynum + baseProductTodayCount.getRequestNum();
                        bdaysuccnum = bdaysuccnum + baseProductTodayCount.getSuccessNum();

                    }

                    alarmNotice.setApiCode(listNew.get(i));
                    noticeNum = noticeNum + alarmNoticeService.getAlarmNotice(alarmNotice);

                    baseProductTps = baseProductTps + getTpsByApiCode(listNew.get(i), date);

                }
                json.put("requestNum", baseProductNum);
                json.put("requestDayNum", bdaynum);
                json.put("requestDaySuccessNum", bdaysuccnum);
                json.put("alarmNum", noticeNum);
                long baseProductRequestPeak = tpsService.queryTpsByDate(date.substring(0, 8), listNew);
                if (baseProductTps > baseProductRequestPeak) {
                    baseProductRequestPeak = baseProductTps;
                }
                json.put("requestTps", baseProductTps);
                json.put("requestPeak", baseProductRequestPeak + "");
                json.put("requestPeakTime", date);
                json.put("linkNum", getLinkNum());
                return R.data(json);
            //api发布
            case "4":
                com.dhcc.bpm.modules.api.entity.Api api = apiService.getById(tpsEntity.getApiId());
                gatewayLog.setOpcApiCode(api.getApiCode());
                json.put("requestNum", gatewayLogService.queryCount(gatewayLog));
                //计算·日交易量
                gatewayLog.setRequestDate(DateUtils.date());
                TodayRequestNum apiTodayCount = gatewayLogService.queryToDayCount(gatewayLog);
                json.put("requestDayNum", apiTodayCount == null ? 0 : apiTodayCount.getRequestNum());
                json.put("requestDaySuccessNum", apiTodayCount == null ? 0 : apiTodayCount.getSuccessNum());
                alarmNotice.setApiCode(api.getApiCode());
                json.put("alarmNum", alarmNoticeService.getAlarmNotice(alarmNotice));
                Long apiTps = getTpsByApiCode(api.getApiCode(), date);
                json.put("requestTps", apiTps);
                apiList.add(api.getApiCode());
                long apiRequestPeak = tpsService.queryTpsByDate(date.substring(0, 8), apiList);
                if (apiTps > apiRequestPeak) {
                    apiRequestPeak = apiTps;
                }
                json.put("requestPeak", apiRequestPeak + "");
                json.put("requestPeakTime", date);
                json.put("linkNum", getLinkNum());
                return R.data(json);
            //应用产品
            case "5":
                Long productTps = 0L;
                Long productNum = 0L;
                Long pdaynum = 0L;
                Long pdaysuccnum = 0L;
                Integer prodNoticeNum = 0;
                List<com.dhcc.bpm.modules.api.entity.Api> prodApi = apiService.getProdApiByProductId(tpsEntity.getProductId());
                for (com.dhcc.bpm.modules.api.entity.Api opcApi : prodApi) {
                    gatewayLog.setOpcApiCode(opcApi.getApiCode());
                    productNum = productNum + gatewayLogService.queryCount(gatewayLog);
                    //计算·日交易量
                    gatewayLog.setRequestDate(DateUtils.date());
                    TodayRequestNum productCount = gatewayLogService.queryToDayCount(gatewayLog);
                    if (null != productCount) {
                        pdaynum = pdaynum + productCount.getRequestNum();
                        pdaysuccnum = pdaysuccnum + productCount.getSuccessNum();

                    }

                    alarmNotice.setApiCode(opcApi.getApiCode());
                    prodNoticeNum = prodNoticeNum + alarmNoticeService.getAlarmNotice(alarmNotice);
                    productTps = productTps + getTpsByApiCode(opcApi.getApiCode(), date);
                    apiList.add(opcApi.getApiCode());
                }
                json.put("requestNum", productNum);
                json.put("requestDayNum", pdaynum);
                json.put("requestDaySuccessNum", pdaysuccnum);
                json.put("alarmNum", prodNoticeNum);

                json.put("requestTps", productTps);

                long productRequestPeak = tpsService.queryTpsByDate(date.substring(0, 8), apiList);
                if (productTps > productRequestPeak) {
                    productRequestPeak = productTps;
                }
                json.put("requestPeak", productRequestPeak);
                json.put("requestPeakTime", date);
                json.put("linkNum", getLinkNum());
                return R.data(json);
            default:
                json.put("requestNum", gatewayLogService.queryCount(gatewayLog));
                //计算·日交易量
                gatewayLog.setRequestDate(DateUtils.date());
                TodayRequestNum count = gatewayLogService.queryToDayCount(gatewayLog);
                json.put("requestDayNum", count == null ? 0 : count.getRequestNum());
                json.put("requestDaySuccessNum", count == null ? 0 : count.getSuccessNum());
                json.put("alarmNum", alarmNoticeService.getAlarmNotice(alarmNotice));
                Long defTps = getAllTps(date);
                json.put("requestTps", defTps);

                long defRequestPeak = tpsService.queryTpsByDate(date.substring(0, 8), null);
                if (defTps > defRequestPeak) {
                    defRequestPeak = defTps;
                }

                json.put("requestPeak", defRequestPeak + "");
                json.put("requestPeakTime", date);
                json.put("linkNum", getLinkNum());
                return R.data(json);
        }
    }

    private static final Long MINUTES = TimeUnit.MINUTES.toMillis(1);

    public Long getTpsByApiCode(String apiCode, String date) {
        Long tps = 0L;
        String patternKey = "tps:" + date + ":" + apiCode;
        List<String> keySet = redisUtil.scan(patternKey);
        Iterator iterator = keySet.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next().toString();
            String value = stringRedisTemplate.opsForValue().get(key);
            logger.info("读取到tps的key:[{}]的值为：[{}]", key, value);
            tps = tps + Long.valueOf(value);
        }
        return tps;
    }

//    @Scheduled(cron = "0 0/1 * * * ?")
    public void tpsStatistics() {
        //分钟定时任务统计2分钟前的tps数据入库
        String patternKey = "tps:" + DateUtils.dateMinute(-1) + "*";
        logger.info("执行tps入库定时任务开始！");
        List<String> keySet = redisUtil.scan(patternKey);
        Iterator iterator = keySet.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next().toString();
            String value = stringRedisTemplate.opsForValue().get(key);
            logger.info("读取到tps的key:[{}]的值为：[{}]", key, value);
            if (StringUtil.isNotEmpty(value)) {
                Tps tps = new Tps();
                int str = key.lastIndexOf(":");
                String requestTime = key.substring(4, str);
                tps.setApiCode(key.substring(str + 1, key.length()));
                tps.setTpsDate(requestTime.substring(0, 8));
                tps.setTpsTime(requestTime.substring(8, requestTime.length()));
                tps.setTps(Long.valueOf(value));
                tps.setCreateTime(DateUtil.now());
                if (tpsService.save(tps)) {
                    stringRedisTemplate.delete(key);
                }
            }
        }
        tpsStatistics(patternKey.substring(0, 14) + "*");
    }

    @GetMapping("/tpsStatistics")
    public void tpsStatistics(String patternKey) {
        logger.info("执行tps入库定时任务开始！key:[{}]", patternKey);
        List<String> keySet = redisUtil.scan(patternKey);
        Iterator iterator = keySet.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next().toString();
            String value = stringRedisTemplate.opsForValue().get(key);
            logger.info("读取到tps的key:[{}]的值为：[{}]", key, value);
            if (StringUtil.isNotEmpty(value)) {
                Tps tps = new Tps();
                int str = key.lastIndexOf(":");
                String requestTime = key.substring(4, str);
                tps.setApiCode(key.substring(str + 1, key.length()));
                tps.setTpsDate(requestTime.substring(0, 8));
                tps.setTpsTime(requestTime.substring(8, requestTime.length()));
                tps.setTps(Long.valueOf(value));
                tps.setCreateTime(DateUtil.now());
                if (tpsService.save(tps)) {
                    stringRedisTemplate.delete(key);
                }
            }
        }
    }

    @Scheduled(cron = "0 0 1 * * ?")
    public void tpsPeakStatistics() {
        String tpsDate = DateUtils.getPastDate(-1, "YYYYMMdd");
        logger.info("执行统计日期为：[{}]号的tps峰值定时任务开始！", tpsDate);
        tpsStatistics("tps:" + tpsDate + "*");
        List<String> apiCodeList = tpsService.getApiCodeList(tpsDate);
        apiCodeList.forEach(apiCode -> {
            //统计每天api的tps峰值
            List<Tps> tpslist = tpsService.getList(apiCode, tpsDate);
            if (tpslist != null && tpslist.size() > 0) {
                TpsPeak tpsPeak = new TpsPeak();
                tpsPeak.setApiCode(tpslist.get(0).getApiCode());
                tpsPeak.setTpsDate(tpslist.get(0).getTpsDate());
                tpsPeak.setTpsTime(tpslist.get(0).getTpsTime());
                tpsPeak.setTpsPeak(tpslist.get(0).getTps());
                tpsPeak.setCreateTime(DateUtil.now());
                tpsPeakService.save(tpsPeak);
            }
        });

        //统计当天所有请求的总峰值
        List<Tps> tps = tpsService.getDayALlTpsPeak(tpsDate);
        if (tps != null && tps.size() > 0) {
            TpsPeak tpsPeak = new TpsPeak();
            tpsPeak.setApiCode("allTps");
            tpsPeak.setTpsDate(tpsDate);
            tpsPeak.setTpsTime(tps.get(0).getTpsTime());
            tpsPeak.setTpsPeak(tps.get(0).getTps());
            tpsPeak.setCreateTime(DateUtil.now());
            tpsPeakService.save(tpsPeak);
        }
        //删除7天前的数据
        int num = tpsService.deleteTpsByDate(DateUtils.getPastDate(-7, "YYYYMMdd"));
        logger.info("删除opc_tps表7天前的数据，共：[{}]条", num);
    }


    public Long getAllTps(String date) {
        //获取10秒前的总tpsDateUtils.dateSecond(0)
        Long tps = 0L;
        String patternKey = "tps:" + date + "*";
        List<String> keySet = redisUtil.scan(patternKey);
        Iterator iterator = keySet.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next().toString();
            String value = stringRedisTemplate.opsForValue().get(key);
            logger.info("读取到tps的key:[{}]的值为：[{}]", key, value);
            tps = tps + Long.valueOf(value);
        }
        return tps;
    }

    public Long getLinkNum() {
        Long linkNum = 0L;
        String patternKey = "linkNum:*";
        List<String> keySet = redisUtil.scan(patternKey);
        Iterator iterator = keySet.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next().toString();
            String value = stringRedisTemplate.opsForValue().get(key);
            logger.info("读取到linkNum的key:[{}]的值为：[{}]", key, value);
            linkNum = linkNum + Long.valueOf(value);
        }
        return linkNum;
    }


    /**
     * @return
     * @Description 首页交易趋势 删原来的前两条，计算现在的10s后的值，add到list里并返回新的tick
     * @Author wjh
     * @Date 2021年1月13日11:33:02
     **/
    @PostMapping("/tradingTrendsByHour")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "首页交易趋势")
    @Log(title = "交易趋势", businessType = BusinessType.SELECT)
    public R<List<TradeTrendsVo>> tradingTrendsByHour(@RequestBody String jsonStr) {
        logger.info("请求参数：{}", jsonStr);
        // 先将字符串转换为JSON对象
        com.alibaba.fastjson.JSONObject jsonObj = com.alibaba.fastjson.JSONObject.parseObject(jsonStr);
        String env = jsonObj.getString("env");
        List<TradeTrendsVo> tradeTrendsVos = JSONArray.parseArray(jsonObj.getJSONArray("tradeTrendsVos").toJSONString(), TradeTrendsVo.class);
        if (tradeTrendsVos.size() > 3) {
            tradeTrendsVos.remove(0);
            tradeTrendsVos.remove(0);
        }
        if (tradeTrendsVos == null || tradeTrendsVos.size() < 1) {
            return R.data(tradeTrendsVos);
        }
        TradeTrendsVo tradeTrendsVo = tradeTrendsVos.get(tradeTrendsVos.size() - 1);
        //加10s后的时间
        String requestTime = DateUtils.plusLocalTime(tradeTrendsVo.getRequestTime());

        LocalDate localDate = LocalDate.now();
        String today = localDate.format(DateTimeFormatter.ofPattern("YYYYMMdd"));

        if (Integer.valueOf(tradeTrendsVo.getRequestTime().substring(0, 2)) > Integer.valueOf(requestTime.substring(0, 2))) {
            //最后一条数据的时间  >  算出来的时间   说明跨天了。  20210101 23:59:59   20210102 00:00:09
            today = DateUtils.plusLocalDate(today);
        }
        // 本部门API列表
        Query query = new Query();
        query.setCurrent(1);
        query.setSize(999999999); // 不分页
        ApiVO api = new ApiVO();
        IPage<ApiVO> page = apiService.listInfo(Condition.getPage(query), api); // 查当前登录部门API列表信息
        List<String> apiCodeList = new ArrayList<>();
        if (page.getRecords() != null && page.getRecords().size() > 0) {
            for (ApiVO apiVO : page.getRecords()) {
                apiCodeList.add(apiVO.getApiCode());
            }
        }
        GatewayLogMinuteVO gatewayLogMinuteVO = new GatewayLogMinuteVO();
        gatewayLogMinuteVO.setEnv(env);

        gatewayLogMinuteVO.setApiCodeList(apiCodeList);

        String endTime = today + requestTime.replace(":", "");
//        gatewayLogMinuteVO.setStartDate(today + tradeTrendsVo.getRequestTime().replace(":", ""));
        gatewayLogMinuteVO.setStartDate(today + tradeTrendsVos.get(0).getRequestTime().replace(":", ""));
        gatewayLogMinuteVO.setEndDate(endTime);
        gatewayLogMinuteVO.setSize(60);
        gatewayLogMinuteVO.setPage(1);
        List<TradeVolumnVo> tradeVolumnVos = gatewayLogMinuteService.countGatewayLogMinuteByTime(gatewayLogMinuteVO);
        Double suc;
        Double res;
        if (tradeVolumnVos.size() > 0) {
            TradeTrendsVo tradeTrendsVo2 = new TradeTrendsVo();
            tradeTrendsVo2.setRequestTime(requestTime);
            tradeTrendsVo2.setNum(tradeVolumnVos.get(0).getSuccessNum());
            suc = (double) tradeVolumnVos.get(0).getSuccessNum() / (double) (tradeVolumnVos.get(0).getFail() + tradeVolumnVos.get(0).getSuccessNum());
            res = (double) tradeVolumnVos.get(0).getResponseNum() / (double) (tradeVolumnVos.get(0).getFail() + tradeVolumnVos.get(0).getSuccessNum());
            //计算成功率
            tradeTrendsVo2.setSuccessRate(suc == 0.0 ? 1 : suc);
            //计算响应率
            tradeTrendsVo2.setResponseRate(res == 0.0 ? 1 : res);
            tradeTrendsVo2.setType("交易成功数");
            TradeTrendsVo tradeTrendsVo1 = new TradeTrendsVo();
            tradeTrendsVo1.setRequestTime(requestTime);
            tradeTrendsVo1.setNum(tradeVolumnVos.get(0).getFail());
            suc = (double) tradeVolumnVos.get(0).getSuccessNum() / (double) (tradeVolumnVos.get(0).getFail() + tradeVolumnVos.get(0).getSuccessNum());
            res = (double) tradeVolumnVos.get(0).getResponseNum() / (double) (tradeVolumnVos.get(0).getFail() + tradeVolumnVos.get(0).getSuccessNum());
            //计算成功率
            tradeTrendsVo1.setSuccessRate(suc == 0.0 ? 1 : suc);
            //计算响应率
            tradeTrendsVo1.setResponseRate(res == 0.0 ? 1 : res);
            tradeTrendsVo1.setType("交易失败数");
            tradeTrendsVos.add(tradeTrendsVo2);
            tradeTrendsVos.add(tradeTrendsVo1);
        } else {
            TradeTrendsVo tradeTrendsVo2 = new TradeTrendsVo();
            tradeTrendsVo2.setRequestTime(requestTime);
            tradeTrendsVo2.setNum(0L);
            tradeTrendsVo2.setType("交易成功数");
            suc = 0.0;
            res = 0.0;
            //计算成功率
            tradeTrendsVo2.setSuccessRate(suc == 0.0 ? 1 : suc);
            //计算响应率
            tradeTrendsVo2.setResponseRate(res == 0.0 ? 1 : res);
            TradeTrendsVo tradeTrendsVo1 = new TradeTrendsVo();
            tradeTrendsVo1.setRequestTime(requestTime);
            tradeTrendsVo1.setNum(0L);
            tradeTrendsVo1.setType("交易失败数");
            //计算成功率
            tradeTrendsVo1.setSuccessRate(suc == 0.0 ? 1 : suc);
            //计算响应率
            tradeTrendsVo1.setResponseRate(res == 0.0 ? 1 : res);
            tradeTrendsVos.add(tradeTrendsVo2);
            tradeTrendsVos.add(tradeTrendsVo1);
        }

        String temp2 = today + tradeTrendsVos.get(0).getRequestTime().replace(":", "");//开始时间
        List<String> ticks3 = new ArrayList<>();
        ticks3.add(DateUtils.getDateHHmmss(temp2));
        while (temp2.compareTo(endTime) < 0) {
            //时间加10min
            String addDate = DateUtils.getAddTenMinute(temp2, 600000);
            ticks3.add(DateUtils.getDateHHmmss(addDate));//去掉年月日
            temp2 = addDate;
        }
        TradeTrendsVo tradeTrendsVo0 = tradeTrendsVos.get(0);
        tradeTrendsVo0.setTicks(ticks3);
        tradeTrendsVos.set(0, tradeTrendsVo0);
        return R.data(tradeTrendsVos);
    }

    /**
     * @return
     * @Description 首页交易趋势 删原来的前两条，计算现在的1min后的值，add到list里并返回新的tick
     * @Author wjh
     * @Date 2021年1月13日11:33:02
     **/
    @PostMapping("/tradingTrendsByDay")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "首页交易趋势")
    @Log(title = "交易趋势", businessType = BusinessType.SELECT)
    public R<List<TradeTrendsVo>> tradingTrendsByDay(@RequestBody String jsonStr) {
        // 先将字符串转换为JSON对象
        com.alibaba.fastjson.JSONObject jsonObj = com.alibaba.fastjson.JSONObject.parseObject(jsonStr);
        TrendsListVO trendsListVO = jsonObj.toJavaObject(TrendsListVO.class);
        List<TradeTrendsVo> tradeTrendsVos = trendsListVO.getTradeTrendsVos();

        tradeTrendsVos.remove(0);
        tradeTrendsVos.remove(0);
        TradeTrendsVo tradeTrendsVo = tradeTrendsVos.get(tradeTrendsVos.size() - 1);
        //加1min后的时间
        String startTime = tradeTrendsVo.getRequestTime() + "00";
        String requestTime = DateUtils.getAddTenMinute(tradeTrendsVo.getRequestTime() + "00", 60000);
        // 本部门API列表
        Query query = new Query();
        query.setCurrent(1);
        query.setSize(999999999); // 不分页
        ApiVO api = new ApiVO();
        IPage<ApiVO> page = apiService.listInfo(Condition.getPage(query), api); // 查当前登录部门API列表信息
        List<String> apiCodeList = new ArrayList<>();
        if (page.getRecords() != null && page.getRecords().size() > 0) {
            for (ApiVO apiVO : page.getRecords()) {
                apiCodeList.add(apiVO.getApiCode());
            }
        }
        GatewayLogMinuteVO gatewayLogMinuteVO = new GatewayLogMinuteVO();
        gatewayLogMinuteVO.setEnv("0");

        gatewayLogMinuteVO.setApiCodeList(apiCodeList);
        gatewayLogMinuteVO.setStartDate(startTime);
        gatewayLogMinuteVO.setEndDate(requestTime);
        List<TradeVolumnVo> tradeVolumnVos = gatewayLogMinuteService.countGatewayLogMinuteByTime(gatewayLogMinuteVO);
        if (tradeVolumnVos.size() > 0) {
            TradeTrendsVo tradeTrendsVo2 = new TradeTrendsVo();
            tradeTrendsVo2.setRequestTime(requestTime.substring(0, 12));
            tradeTrendsVo2.setNum(tradeVolumnVos.get(0).getSuccessNum());
            tradeTrendsVo2.setType("交易成功数");
            TradeTrendsVo tradeTrendsVo1 = new TradeTrendsVo();
            tradeTrendsVo1.setRequestTime(requestTime.substring(0, 12));
            tradeTrendsVo1.setNum(tradeVolumnVos.get(0).getFail());
            tradeTrendsVo1.setType("交易失败数");
            tradeTrendsVos.add(tradeTrendsVo2);
            tradeTrendsVos.add(tradeTrendsVo1);
        } else {
            TradeTrendsVo tradeTrendsVo2 = new TradeTrendsVo();
            tradeTrendsVo2.setRequestTime(requestTime.substring(0, 12));
            tradeTrendsVo2.setNum(0L);
            tradeTrendsVo2.setType("交易成功数");
            TradeTrendsVo tradeTrendsVo1 = new TradeTrendsVo();
            tradeTrendsVo1.setRequestTime(requestTime.substring(0, 12));
            tradeTrendsVo1.setNum(0L);
            tradeTrendsVo1.setType("交易失败数");
            tradeTrendsVos.add(tradeTrendsVo2);
            tradeTrendsVos.add(tradeTrendsVo1);
        }

        String temp = startTime;//开始时间
        List<String> ticks3 = new ArrayList<>();
        ticks3.add(temp.substring(0, 12));
        while (temp.compareTo(requestTime) < 0) {
            //时间加2小时
            String addDate = DateUtils.getAddTenMinute(temp, 7200000);
            ticks3.add(addDate.substring(0, 12));
            temp = addDate;
        }
        TradeTrendsVo tradeTrendsVo0 = tradeTrendsVos.get(0);
        tradeTrendsVo0.setTicks(ticks3);
        tradeTrendsVos.set(0, tradeTrendsVo0);
        return R.data(tradeTrendsVos);
    }

    @GetMapping("/test")
    public R test() {
        Query query1 = new Query();
        query1.setCurrent(1);
        query1.setSize(500);
        GatewayLogMinuteVO gatewayLogMinuteVO = new GatewayLogMinuteVO();
        gatewayLogMinuteVO.setStartDate("20210113170000");
        gatewayLogMinuteVO.setEndDate("20210113173000");
        gatewayLogMinuteVO.setEnv("0");
        IPage<TradeVolumnVo> page1 = gatewayLogMinuteService.countGatewayLogMinuteByTimeByPage(Condition.getPage(query1), gatewayLogMinuteVO);
        return R.data(page1);
    }

    /**
     * @param type
     * @param gatewayLogDayVO
     * @return
     * @Description 首页tps交易趋势
     * @Author xiafayu
     * @Date 2020/2/24 15:19
     **/
    @GetMapping("/tpsTradingTrends/{type}")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "首页交易趋势")
    @Log(title = "交易趋势", businessType = BusinessType.SELECT)
    public R<List<TpsModelVO>> tpsTradingTrends(@PathVariable("type") String type, GatewayLogDayVO gatewayLogDayVO) throws Exception {
        boolean flag = false;
        String nowDate = DateUtils.dateTime();
        String[] date = DateUtils.getDateTimeAddOneHour(-1);
        String[] dateArr = DateUtils.getDateTimeAddOneHour(-24);//获取到24小时前时间和现在时间
        // 本部门API列表
        Query query = new Query();
        query.setCurrent(1);
        query.setSize(999999999); // 不分页
        ApiVO api = new ApiVO();
        List<Long> ids = new ArrayList<>();
        if (gatewayLogDayVO.getApiId() != null) {
            ids.add(gatewayLogDayVO.getApiId());
            api.setApiIds(ids);
            flag = true;
        }
        if (gatewayLogDayVO.getBaseProductId() != null) {
            //基础产品页面传进来
            List<Long> listNew = getBaseProductList(gatewayLogDayVO.getBaseProductId());
            api.setApiIds(listNew);
            flag = true;
        }
        if (gatewayLogDayVO.getProductId() != null) {
            //应用产品页面传进来
            List<Long> apiIds = apiService.getProdApiIdsByProductId(gatewayLogDayVO.getProductId());
            api.setApiIds(apiIds);
            flag = true;
        }
        if (gatewayLogDayVO.getOpcSysId() != null) {
            //系统页面传进来----系统id，找到基础产品id，在找到api的id
            List<Long> apiIds = apiService.getApiIdsBySysId(String.valueOf(gatewayLogDayVO.getOpcSysId()));
            api.setApiIds(apiIds);
            flag = true;
        }

        List<String> apiCodeList = new ArrayList<String>();
        if (flag) {
            IPage<ApiVO> page = apiService.listInfo(Condition.getPage(query), api); // 查当前登录部门API列表信息
            if (page.getRecords() != null && page.getRecords().size() > 0) {
                for (ApiVO apiVO : page.getRecords()) {
                    apiCodeList.add(apiVO.getApiCode());
                }
            }
        } else {
            if ("week".equals(type) || "month".equals(type) || "year".equals(type)) {
                apiCodeList.add("allTps");
            }
        }
        gatewayLogDayVO.setApiCodeList(apiCodeList);

        switch (type) {
            case "hour":
                gatewayLogDayVO.setBeginDate(date[0]);
                gatewayLogDayVO.setEndDate(date[1]);
                List<TpsModelVO> tpsHourList = tpsService.getHourList(gatewayLogDayVO);
                return R.data(getHourTps(date, tpsHourList));
            case "day":
                gatewayLogDayVO.setBeginDate(dateArr[0]);
                gatewayLogDayVO.setEndDate(dateArr[1]);
                List<TpsModelVO> tpsDayList = tpsService.getDayList(gatewayLogDayVO);
                return R.data(getTenMinuteTps(dateArr, tpsDayList));
            case "week":
                String[] dateArr2 = new String[2];
                dateArr2[0] = DateUtils.dateTime().substring(0, 12) + "00";
                dateArr2[1] = DateUtils.getPastDate(-6, "yyyyMMddHHmmss").substring(0, 12) + "00";//一周前的日期
                gatewayLogDayVO.setBeginDate(dateArr2[1]);
                gatewayLogDayVO.setEndDate(dateArr2[0]);
                List<TpsModelVO> tpsDayList2 = tpsService.getDayList(gatewayLogDayVO);
                return R.data(getWeeksTps(dateArr2, tpsDayList2));
            case "month":
                String[] dateArr3 = new String[2];
                dateArr3[0] = DateUtils.dateTime();
                dateArr3[1] = DateUtils.getLastDay(dateArr3[0], 29) + "000000";//一月前的日期
                gatewayLogDayVO.setBeginDate(dateArr3[1]);
                gatewayLogDayVO.setEndDate(dateArr3[0]);
                List<TpsModelVO> tpsDayList3 = tpsService.getDayList(gatewayLogDayVO);
                return R.data(getMonthsTps(dateArr3, tpsDayList3));
            case "year":
                String[] dateArr4 = new String[2];
                dateArr4[0] = DateUtils.dateTime().substring(0, 4) + "0101";
                dateArr4[1] = DateUtils.dateTime().substring(0, 4) + "1231";
                gatewayLogDayVO.setBeginDate(dateArr4[0]);
                gatewayLogDayVO.setEndDate(dateArr4[1]);
                List<TpsModelVO> tpsDayList4 = tpsPeakService.countNumBydate(gatewayLogDayVO);
                return R.data(getYears365Tps(DateUtils.dateTime().substring(0, 4), tpsDayList4));
            default:
                break;
        }

        return R.data(null);
    }

    /**
     * @Author wangjinghan
     * @Description 得到指定时间区域内的【每10s】间隔的数据
     * @date: 2021/1/6 16:24
     */
    private List<TpsModelVO> getHourTps(String[] date, List<TpsModelVO> tradeTrendsLists) {
        List<TpsModelVO> tradeVoListData = new LinkedList<>();

        //以10s分割
        Map<Long, Double> tpsNumMap2 = new LinkedHashMap<>();
        Map<Long, Long> numMap2 = new LinkedHashMap<>();
        String temp = date[0];//开始时间
        tpsNumMap2.put(Long.valueOf(date[0]), 0D);
        numMap2.put(Long.valueOf(date[0]), 0L);
        while (temp.compareTo(date[1]) < 0) {
            //时间加10s
            String addDate = DateUtils.getAddOneHour(temp);
            tpsNumMap2.put(Long.valueOf(addDate), 0D);
            numMap2.put(Long.valueOf(addDate), 0L);
            temp = addDate;
        }

        if (tradeTrendsLists != null && tradeTrendsLists.size() > 0) {
            for (TpsModelVO tps : tradeTrendsLists) {
                String d = tps.getRequestTime();
                Long hour = Long.valueOf(d.substring(0, d.length() - 2) + date[0].substring(12, 14));
                double sucNum = tps.getNum();
                if (tpsNumMap2.get(hour) != null) {
                    sucNum = tpsNumMap2.get(hour) + sucNum;
                }
                tpsNumMap2.put(hour, sucNum);
                Long num = numMap2.get(hour) == null ? 0L : numMap2.get(hour);
                numMap2.put(hour, num + 1);
            }
        }

        for (Long hour2 : tpsNumMap2.keySet()) {
            TpsModelVO tradeTrendsVo = new TpsModelVO();
            tradeTrendsVo.setRequestTime(hour2.toString());
            BigDecimal tps = new BigDecimal(0);
            if (tpsNumMap2.get(hour2) != 0) {
                tps = new BigDecimal(tpsNumMap2.get(hour2) / numMap2.get(hour2));
            }
            tradeTrendsVo.setNum(tps.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            tradeTrendsVo.setType("TPS值");
            tradeVoListData.add(tradeTrendsVo);
        }
        return tradeVoListData;
    }

    /**
     * @Author wangjinghan
     * @Description 每天一个点
     * @date: 2022年3月1日09:25:00
     * date yyyy  当前年份
     */
    private List<TpsModelVO> getYears365Tps(String year, List<TpsModelVO> tradeTrendsLists) {


        int yearDay = Integer.valueOf(year);  //获取当年 天数
        boolean isRun = false;  //是否是闰年
        if (yearDay % 4 == 0 && yearDay % 100 != 0 || yearDay % 400 == 0) {
            isRun = true;
        }
        List<TpsModelVO> oneYearList = new ArrayList<>(isRun ? 366 : 355);
        for (int i = 1; i <= 12; i++) {
            for (int y = 1; y <= 31; y++) {
                if (y == 29 && i == 2 && !isRun) {
                    //不是闰年
                    break;
                }
                if (y > 29 && i == 2) {
                    break;
                }

                if (y == 31 && (i == 4 || i == 6 || i == 9 || i == 11)) {
                    //共30天
                    break;
                }
                String requestTime = "";
                if (i >= 10 && y >= 10) {
                    requestTime = year + i + y;
                } else if (i < 10 && y >= 10) {
                    requestTime = year + "0" + i + y;
                } else {
                    requestTime = year + "0" + i + "0" + y;
                }
                String finalRequestTime = requestTime;
                Optional<TpsModelVO> trendsVoOptional = tradeTrendsLists.stream().filter(item -> finalRequestTime.equals(item.getRequestTime())).findFirst();
                if (!trendsVoOptional.isPresent()) {
                    TpsModelVO tradeTrendsVo = new TpsModelVO();
                    tradeTrendsVo.setRequestTime(requestTime);
                    tradeTrendsVo.setType("TPS值");
                    tradeTrendsVo.setNum(0D);
                    oneYearList.add(tradeTrendsVo);
                } else {
                    oneYearList.add(trendsVoOptional.get());
                }

            }
        }
        return oneYearList;

    }

    /**
     * @Author wangjinghan
     * @Description 得到指定时间区域内的【每5天】间隔的数据
     * @date: 2022年3月1日09:25:00
     * date yyyy  当前年份
     */
    private List<TpsModelVO> getYearsTps(String date, List<TpsModelVO> tradeTrendsLists) {
        List<TpsModelVO> tradeVoListData = new LinkedList<>();
        Map<Long, Double> tpsNumMap2 = new LinkedHashMap<>();
        Map<Long, Long> numMap2 = new LinkedHashMap<>();

        for (int i = 1; i <= 12; i++) {
            if (i < 10) {
                numMap2.put(Long.valueOf(date + "0" + i + "01"), 0L);
                numMap2.put(Long.valueOf(date + "0" + i + "05"), 0L);
                numMap2.put(Long.valueOf(date + "0" + i + "10"), 0L);
                numMap2.put(Long.valueOf(date + "0" + i + "15"), 0L);
                numMap2.put(Long.valueOf(date + "0" + i + "20"), 0L);
                numMap2.put(Long.valueOf(date + "0" + i + "25"), 0L);

                tpsNumMap2.put(Long.valueOf(date + "0" + i + "01"), 0D);
                tpsNumMap2.put(Long.valueOf(date + "0" + i + "05"), 0D);
                tpsNumMap2.put(Long.valueOf(date + "0" + i + "10"), 0D);
                tpsNumMap2.put(Long.valueOf(date + "0" + i + "15"), 0D);
                tpsNumMap2.put(Long.valueOf(date + "0" + i + "20"), 0D);
                tpsNumMap2.put(Long.valueOf(date + "0" + i + "25"), 0D);
            } else {
                numMap2.put(Long.valueOf(date + i + "01"), 0L);
                numMap2.put(Long.valueOf(date + i + "05"), 0L);
                numMap2.put(Long.valueOf(date + i + "10"), 0L);
                numMap2.put(Long.valueOf(date + i + "15"), 0L);
                numMap2.put(Long.valueOf(date + i + "20"), 0L);
                numMap2.put(Long.valueOf(date + i + "25"), 0L);

                tpsNumMap2.put(Long.valueOf(date + i + "01"), 0D);
                tpsNumMap2.put(Long.valueOf(date + i + "05"), 0D);
                tpsNumMap2.put(Long.valueOf(date + i + "10"), 0D);
                tpsNumMap2.put(Long.valueOf(date + i + "15"), 0D);
                tpsNumMap2.put(Long.valueOf(date + i + "20"), 0D);
                tpsNumMap2.put(Long.valueOf(date + i + "25"), 0D);
            }
        }


        if (tradeTrendsLists != null && tradeTrendsLists.size() > 0) {
            for (TpsModelVO tradeVolumnVo : tradeTrendsLists) {
                //yyyyMMdd
                int day = Integer.valueOf(tradeVolumnVo.getRequestTime().substring(6));
                String d = "";
                Long dayInt = 0L;
                if (day < 5) {
                    d = tradeVolumnVo.getRequestTime().substring(0, 6) + "01";
                    dayInt = Long.valueOf(d); //yyyymmddHHmm
                } else if (day < 10) {
                    d = tradeVolumnVo.getRequestTime().substring(0, 6) + "05";
                    dayInt = Long.valueOf(d); //yyyymmddHHmm
                } else if (day < 15) {
                    d = tradeVolumnVo.getRequestTime().substring(0, 6) + "10";
                    dayInt = Long.valueOf(d); //yyyymmddHHmm
                } else if (day < 20) {
                    d = tradeVolumnVo.getRequestTime().substring(0, 6) + "15";
                    dayInt = Long.valueOf(d); //yyyymmddHHmm
                } else if (day < 25) {
                    d = tradeVolumnVo.getRequestTime().substring(0, 6) + "20";
                    dayInt = Long.valueOf(d); //yyyymmddHHmm
                } else if (day < 31) {
                    d = tradeVolumnVo.getRequestTime().substring(0, 6) + "25";
                    dayInt = Long.valueOf(d); //yyyymmddHHmm
                }

                double sucNum = tradeVolumnVo.getNum();

                if (tpsNumMap2.get(dayInt) != null) {
                    sucNum = tpsNumMap2.get(dayInt) + sucNum;
                    tpsNumMap2.put(dayInt, sucNum);
                    numMap2.put(dayInt, numMap2.get(dayInt) + 1);
                }

            }
        }

        for (Long hour2 : tpsNumMap2.keySet()) {
            TpsModelVO tradeTrendsVo = new TpsModelVO();
            tradeTrendsVo.setRequestTime(hour2.toString());
            tradeTrendsVo.setType("TPS值");
            BigDecimal tps = new BigDecimal(0);
            if (tpsNumMap2.get(hour2) != 0) {
                tps = new BigDecimal(tpsNumMap2.get(hour2) / numMap2.get(hour2));
            }
            tradeTrendsVo.setNum(tps.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            tradeVoListData.add(tradeTrendsVo);
        }
        return tradeVoListData;
    }

    /**
     * @Author wangjinghan
     * @Description 得到指定时间区域内的【每12小时】间隔的数据
     * @date: 2022年3月1日09:25:00
     */
    private List<TpsModelVO> getMonthsTps(String[] date, List<TpsModelVO> tradeTrendsLists) {
        List<TpsModelVO> tradeVoListData = new LinkedList<>();
        Map<Long, Double> tpsNumMap2 = new LinkedHashMap<>();
        Map<Long, Long> numMap2 = new LinkedHashMap<>();
        //以12h分割
        String temp = date[1];//开始时间
        String endDate = date[0].substring(0, 8) + "000000";//开始时间
        tpsNumMap2.put(Long.valueOf(date[1].substring(0, 12)), 0D);    //开始时间成功数
        numMap2.put(Long.valueOf(date[1].substring(0, 12)), 0L);   //开始时间失败数
        while (Long.valueOf(temp) < Long.valueOf(endDate)) {       //把区间内 每间隔12小时的点存到map里，后续进行更新
            //时间加12小时
            String addDate = DateUtils.getAddTenMinute(temp, 43200000);
            tpsNumMap2.put(Long.valueOf(addDate.substring(0, 12)), 0D);
            numMap2.put(Long.valueOf(addDate.substring(0, 12)), 0L);
            temp = addDate;
        }


        if (tradeTrendsLists != null && tradeTrendsLists.size() > 0) {
            for (TpsModelVO tradeVolumnVo : tradeTrendsLists) {
                int hourItem = Integer.valueOf(tradeVolumnVo.getRequestTime().substring(8, 10));
                String d = "";
                Long hour = 0L;
                if (hourItem >= 12) {
                    d = tradeVolumnVo.getRequestTime().substring(0, 8) + "1200";
                    hour = Long.valueOf(d); //yyyymmddHHmm
                } else {
                    d = tradeVolumnVo.getRequestTime().substring(0, 8) + "0000";
                    hour = Long.valueOf(d); //yyyymmddHHmm
                }

                double sucNum = tradeVolumnVo.getNum();

                if (tpsNumMap2.get(hour) != null) {
                    sucNum = tpsNumMap2.get(hour) + sucNum;
                    tpsNumMap2.put(hour, sucNum);
                    numMap2.put(hour, numMap2.get(hour) + 1);
                }

            }
        }

        for (Long hour2 : tpsNumMap2.keySet()) {
            TpsModelVO tradeTrendsVo = new TpsModelVO();
            tradeTrendsVo.setRequestTime(hour2.toString());
            tradeTrendsVo.setType("TPS值");
            BigDecimal tps = new BigDecimal(0);
            if (tpsNumMap2.get(hour2) != 0) {
                tps = new BigDecimal(tpsNumMap2.get(hour2) / numMap2.get(hour2));
            }
            tradeTrendsVo.setNum(tps.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            tradeVoListData.add(tradeTrendsVo);
        }
        return tradeVoListData;
    }

    /**
     * @Author wangjinghan
     * @Description 得到指定时间区域内的【每2小时】间隔的数据
     * @date: 2022年3月1日09:25:00
     */
    private List<TpsModelVO> getWeeksTps(String[] date, List<TpsModelVO> tradeTrendsLists) {
        List<TpsModelVO> tradeVoListData = new LinkedList<>();
        Map<Long, Double> tpsNumMap2 = new LinkedHashMap<>();
        Map<Long, Long> numMap2 = new LinkedHashMap<>();
        //以2h分割
        String temp = date[1].substring(0, 10) + "0000";//开始时间
        String endDate = date[0].substring(0, 10) + "0000";//开始时间
        tpsNumMap2.put(Long.valueOf(date[1].substring(0, 12)), 0D);    //开始时间成功数
        numMap2.put(Long.valueOf(date[1].substring(0, 12)), 0L);   //开始时间失败数
        while (Long.valueOf(temp) < Long.valueOf(endDate)) {       //把区间内 每间隔2小时的点存到map里，后续进行更新
            //时间加2小时
            String addDate = DateUtils.getAddTenMinute(temp, 7200000);
            tpsNumMap2.put(Long.valueOf(addDate.substring(0, 12)), 0D);
            numMap2.put(Long.valueOf(addDate.substring(0, 12)), 0L);
            temp = addDate;
        }


        if (tradeTrendsLists != null && tradeTrendsLists.size() > 0) {
            for (TpsModelVO tradeVolumnVo : tradeTrendsLists) {
                String d = tradeVolumnVo.getRequestTime().substring(0, 10) + "00";
                Long hour = Long.valueOf(d); //yyyymmddHHmm

                double sucNum = tradeVolumnVo.getNum();

                if (tpsNumMap2.get(hour) != null) {
                    sucNum = tpsNumMap2.get(hour) + sucNum;
                    tpsNumMap2.put(hour, sucNum);
                    numMap2.put(hour, numMap2.get(hour) + 1);
                } else {
                    //d -1小时
                    Long hour2 = Long.valueOf(DateUtils.getAddTenMinute(d + "00", -3600000).substring(0, 12)); //yyyymmddHHmm
                    if (tpsNumMap2.get(hour2) != null) {
                        sucNum = tpsNumMap2.get(hour2) + sucNum;
                        tpsNumMap2.put(hour2, sucNum);
                        numMap2.put(hour2, numMap2.get(hour2) + 1);
                    }
                }

            }
        }

        for (Long hour2 : tpsNumMap2.keySet()) {
            TpsModelVO tradeTrendsVo = new TpsModelVO();
            tradeTrendsVo.setRequestTime(hour2.toString());
            tradeTrendsVo.setType("TPS值");
            BigDecimal tps = new BigDecimal(0);
            if (tpsNumMap2.get(hour2) != 0) {
                tps = new BigDecimal(tpsNumMap2.get(hour2) / numMap2.get(hour2));
            }
            tradeTrendsVo.setNum(tps.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            tradeVoListData.add(tradeTrendsVo);
        }
        return tradeVoListData;
    }

    /**
     * @Author wangjinghan
     * @Description 得到指定时间区域内的【每10min】间隔的数据
     * @date: 2021/1/6 16:24
     */
    private List<TpsModelVO> getTenMinuteTps(String[] date, List<TpsModelVO> tradeTrendsLists) {
        List<TpsModelVO> tradeVoListData = new LinkedList<>();
        //以10min分割
        Map<Long, Double> tpsNumMap2 = new LinkedHashMap<>();
        Map<Long, Long> numMap2 = new LinkedHashMap<>();
        String temp = date[0];//开始时间
        tpsNumMap2.put(Long.valueOf(date[0].substring(0, 12)), 0D);
        numMap2.put(Long.valueOf(date[0].substring(0, 12)), 0L);
        while (temp.compareTo(date[1]) < 0) {
            //时间加10s
            String addDate = DateUtils.getAfterTenMinute(temp);
            tpsNumMap2.put(Long.valueOf(addDate.substring(0, 12)), 0D);
            numMap2.put(Long.valueOf(addDate.substring(0, 12)), 0L);
            temp = addDate;
        }

        if (tradeTrendsLists != null && tradeTrendsLists.size() > 0) {
            for (TpsModelVO tradeVolumnVo : tradeTrendsLists) {
                String d = "";
                if (tradeVolumnVo.getRequestTime().length() > 8) {
                    d = tradeVolumnVo.getRequestTime().substring(0, 11) + date[0].substring(11, 12);
                } else {
                    d = tradeVolumnVo.getRequestTime() + date[0].substring(8, 12);
                }
                Long hour = Long.valueOf(d);

                double sucNum = tradeVolumnVo.getNum();

                if (tpsNumMap2.get(hour) != null) {
                    sucNum = tpsNumMap2.get(hour) + sucNum;
                }
                tpsNumMap2.put(hour, sucNum);
                Long num = 1L;
                if (numMap2.get(hour) != null) {
                    num = numMap2.get(hour) + num;
                }
                numMap2.put(hour, num);
            }
        }

        for (Long hour2 : tpsNumMap2.keySet()) {
            TpsModelVO tradeTrendsVo = new TpsModelVO();
            tradeTrendsVo.setRequestTime(hour2.toString());
            tradeTrendsVo.setType("TPS值");
            BigDecimal tps = new BigDecimal(0);
            if (tpsNumMap2.get(hour2) != 0) {
                tps = new BigDecimal(tpsNumMap2.get(hour2) / numMap2.get(hour2));
            }
            tradeTrendsVo.setNum(tps.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            tradeVoListData.add(tradeTrendsVo);
        }
        return tradeVoListData;
    }

    //  获取周/月交易趋势
    private List<TpsModelVO> tpsTradingTrendsWM(String flag, GatewayLogDayVO gatewayLogDayVO, String nowDate) {
        List<TpsModelVO> tradeVoListData = new LinkedList<>();
        List<String> list = new LinkedList<>();
        int len = 0;
        if (flag.equals("week")) {
            try {
                list = DateUtils.getLastDays(nowDate.substring(0, 8), 7);
            } catch (Exception e) {
                logger.error("获取近七日日期列表失败");
            } finally {

            }
            Collections.sort(list);
            len = list.size();
        } else {
            try {
                list = DateUtils.getLastDays(nowDate.substring(0, 8), 30);
            } catch (Exception e) {
                logger.error("获取近30日日期列表失败");
            } finally {

            }
            Collections.sort(list);
            len = list.size();
        }
        gatewayLogDayVO.setBeginDate(list.get(0));
        gatewayLogDayVO.setEndDate(list.get(list.size() - 1));
        List<TpsModelVO> tradeVoLists = new LinkedList<>();
        tradeVoLists = tpsPeakService.countNumBydate(gatewayLogDayVO);
        Map<String, Integer> mapWeek = new LinkedHashMap<String, Integer>(); // 返回
        for (int i = 0; i < len; i++) {
            mapWeek.put(list.get(i), 0);
        }
        for (String key : mapWeek.keySet()) {
            TpsModelVO tradeTrends = new TpsModelVO();
            tradeTrends.setRequestTime(key);
            tradeTrends.setNum(0L);
            tradeTrends.setType("TPS峰值");
            if (tradeVoLists != null && tradeVoLists.size() > 0) {
                for (TpsModelVO tradeTrendsVo : tradeVoLists) {
                    if (key.equals(tradeTrendsVo.getRequestTime())) {
                        tradeTrends.setNum(tradeTrendsVo.getNum());
                        break;
                    }
                }
            }
            tradeVoListData.add(tradeTrends);
        }
        return tradeVoListData;
    }

    //  获取周/月交易趋势
    private List<TpsModelVO> tpsTradingTrendsYear(GatewayLogDayVO gatewayLogDayVO, String nowDate) {
        List<TpsModelVO> tradeVoListData = new LinkedList<>();
        String beginDate = nowDate.substring(0, 4) + "0101";
        String endDate = nowDate.substring(0, 4) + "1231";
        gatewayLogDayVO.setBeginDate(beginDate);
        gatewayLogDayVO.setEndDate(endDate);
        List<TpsModelVO> tradeVoLists = tpsPeakService.countNumByYear(gatewayLogDayVO);
        Map<String, Integer> mapYear = new LinkedHashMap<String, Integer>(); // 返回
        for (int i = 1; i <= 12; i++) {
            mapYear.put(String.valueOf(i), 0);
        }
        for (String key : mapYear.keySet()) {
            TpsModelVO tradeTrends = new TpsModelVO();
            tradeTrends.setRequestTime(key + "月");
            tradeTrends.setNum(0L);
            tradeTrends.setType("TPS峰值");
            if (tradeVoLists != null && tradeVoLists.size() > 0) {
                for (TpsModelVO tradeTrendsVo : tradeVoLists) {
                    tradeTrendsVo.setRequestTime(String.valueOf(Integer.parseInt(tradeTrendsVo.getRequestTime())));
                    if (key.equals(tradeTrendsVo.getRequestTime())) {
                        tradeTrends.setNum(tradeTrendsVo.getNum());
                        break;
                    }
                }
            }
            tradeVoListData.add(tradeTrends);
        }
        return tradeVoListData;
    }
}
